#############################################/
## R-Script - Analyses                      ##
## by: Schimpf, Wuttke, Schoen              ##
## Version: July 17, 2021                   ##
## Last Updated: Feb 4, 2023                ##
## R-Version: 4.1.0.                        ##
#############################################/

################################################################################/
#### /// Functions                                                           ####
################################################################################/

## Functions to alter axes in plots
# Functions for borders: https://stackoverflow.com/questions/10808761/r-style-axes-with-ggplot
# x axis - I
base_breaks_x1 <- function(x){
  b <- pretty(x)
  d <- data.frame(y=-Inf, yend=-Inf, x=min(b), xend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_x_continuous(breaks=b))
}
# y axis I
base_breaks_y1 <- function(x){
  b <- pretty(x)
  d <- data.frame(x=-Inf, xend=-Inf, y=0, yend=1)
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_y_continuous(breaks=seq(0,1, 0.2)))
}
#y axis II
base_breaks_y2 <- function(x){
  b <- pretty(x)
  d <- data.frame(x=-Inf, xend=-Inf, y=0, yend=0.8)
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_y_continuous(breaks=seq(0,1, 0.2)))
}

## x axis II
base_breaks_x3 <- function(x){
  b <- pretty(x)
  d <- data.frame(y=-Inf, yend=-Inf, x=min(b), xend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_x_continuous(breaks=seq(0,4,1)))
}

#y axis III
base_breaks_y3 <- function(x){
  b <- pretty(x)
  d <- data.frame(x=-Inf, xend=-Inf, y=0, yend=1)
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=FALSE),
       scale_y_continuous(breaks=seq(0,1, 0.2)))
}

################################################################################/
#### /// ANALYSES MAIN TEXT                                                ####
################################################################################/

###############################################################################/
#### <<>> Over time correlations prep (Relative stability - 1st Wave-to-Other Waves) ####
###############################################################################/

#### <<<>>> Step 1: Run correlation between pairs of waves ####
corrW5W8 <- cor.test(x=df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, 
                     y=df_GLES17$Populism_Goertz_AbsoluteMinimum_W8, method = 'pearson', exact = FALSE)
corrW5W9 <- cor.test(x=df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, 
                     y=df_GLES17$Populism_Goertz_AbsoluteMinimum_W9, method = 'pearson', exact = FALSE)
corrW5W13 <- cor.test(x=df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, 
                      y=df_GLES17$Populism_Goertz_AbsoluteMinimum_W13, method = 'pearson', exact = FALSE)
corrW5W14 <- cor.test(x=df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, 
                      y=df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, method = 'pearson', exact = FALSE)
corrW5W15 <- cor.test(x=df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, 
                      y=df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, method = 'pearson', exact = FALSE)

#### <<<>>> Step 2A Repeat (for complete observations): Run correlation between pairs of waves ####

# Generate subset of respondents for whom there is valid data in each of the six categorization varibles:
subset_correlation_b <- c("lfdn", "Populism_Goertz_AbsoluteMinimum_W5",
                          "Populism_Goertz_AbsoluteMinimum_W8", "Populism_Goertz_AbsoluteMinimum_W9",
                          "Populism_Goertz_AbsoluteMinimum_W13", "Populism_Goertz_AbsoluteMinimum_W14",
                          "Populism_Goertz_AbsoluteMinimum_W15")
df_GLES17_correlation_Subset_b <- df_GLES17[subset_correlation_b]
df_GLES17_correlation_Subset_b <- df_GLES17_correlation_Subset_b[complete.cases(df_GLES17_correlation_Subset_b), ]

corrW5W8_complete_b <- cor.test(x=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W5, 
                                y=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W8, method = 'pearson', exact = FALSE)
corrW5W9_complete_b <- cor.test(x=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W5, 
                                y=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W9, method = 'pearson', exact = FALSE)
corrW5W13_complete_b <- cor.test(x=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W5, 
                                 y=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W13, method = 'pearson', exact = FALSE)
corrW5W14_complete_b <- cor.test(x=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W5,
                                 y=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W14, method = 'pearson', exact = FALSE)
corrW5W15_complete_b <- cor.test(x=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W5, 
                                 y=df_GLES17_correlation_Subset_b$Populism_Goertz_AbsoluteMinimum_W15, method = 'pearson', exact = FALSE)

#### <<<>>> Step 2B (for complete observations): Run correlation between pairs of waves for multiplied populism scores ####

# Generate subset of respondents for whom there is valid data in each of the six categorization varibles:
subset_correlation_b_mult <- c("lfdn", "Populism_Goertz_Multiplication_W5",
                               "Populism_Goertz_Multiplication_W8", "Populism_Goertz_Multiplication_W9",
                               "Populism_Goertz_Multiplication_W13", "Populism_Goertz_Multiplication_W14",
                               "Populism_Goertz_Multiplication_W15")
df_GLES17_correlation_Subset_b_mult <- df_GLES17[subset_correlation_b_mult]
df_GLES17_correlation_Subset_b_mult <- df_GLES17_correlation_Subset_b_mult[complete.cases(df_GLES17_correlation_Subset_b_mult), ]

corrW5W8_complete_b_mult <- cor.test(x=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W5, 
                                     y=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W8, method = 'pearson', exact = FALSE)
corrW5W9_complete_b_mult <- cor.test(x=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W5, 
                                     y=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W9, method = 'pearson', exact = FALSE)
corrW5W13_complete_b_mult <- cor.test(x=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W5, 
                                      y=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W13, method = 'pearson', exact = FALSE)
corrW5W14_complete_b_mult <- cor.test(x=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W5,
                                      y=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W14, method = 'pearson', exact = FALSE)
corrW5W15_complete_b_mult <- cor.test(x=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W5, 
                                      y=df_GLES17_correlation_Subset_b_mult$Populism_Goertz_Multiplication_W15, method = 'pearson', exact = FALSE)

#### <<<>>> Step 2C (for complete observations): Run correlation between pairs of waves for 2-dimensional minimum populism scores ####

# Generate subset of respondents for whom there is valid data in each of the six categorization varibles:
subset_correlation_c_twodim <- c("lfdn", "Populism_Goertz_AbsoluteMinimum_TwoDim_W5",
                                 "Populism_Goertz_AbsoluteMinimum_TwoDim_W8", "Populism_Goertz_AbsoluteMinimum_TwoDim_W9",
                                 "Populism_Goertz_AbsoluteMinimum_TwoDim_W13", "Populism_Goertz_AbsoluteMinimum_TwoDim_W14",
                                 "Populism_Goertz_AbsoluteMinimum_TwoDim_W15")
df_GLES17_correlation_Subset_c_twodim <- df_GLES17[subset_correlation_c_twodim]
df_GLES17_correlation_Subset_c_twodim <- df_GLES17_correlation_Subset_c_twodim[complete.cases(df_GLES17_correlation_Subset_c_twodim), ]

corrW5W8_complete_c_twodim <- cor.test(x=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W5, 
                                       y=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W8, method = 'pearson', exact = FALSE)
corrW5W9_complete_c_twodim <- cor.test(x=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W5, 
                                       y=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W9, method = 'pearson', exact = FALSE)
corrW5W13_complete_c_twodim <- cor.test(x=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W5, 
                                        y=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W13, method = 'pearson', exact = FALSE)
corrW5W14_complete_c_twodim <- cor.test(x=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W5,
                                        y=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W14, method = 'pearson', exact = FALSE)
corrW5W15_complete_c_twodim <- cor.test(x=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W5, 
                                        y=df_GLES17_correlation_Subset_c_twodim$Populism_Goertz_AbsoluteMinimum_TwoDim_W15, method = 'pearson', exact = FALSE)

#### <<<>>> Step 3: Run correlation for Economic Evaluations ####

# Generate subset of respondents for whom there is valid data in each of the six categorization variables:
subset_correlation_econ <- c("lfdn", "EcoPercSocio_W5", "EcoPercSocio_W8", 
                             "EcoPercSocio_W13", "EcoPercSocio_W14",
                             "EcoPercSocio_W15")
df_GLES17_correlation_Subset_econ <- df_GLES17[subset_correlation_econ]
df_GLES17_correlation_Subset_econ <- df_GLES17_correlation_Subset_econ[complete.cases(df_GLES17_correlation_Subset_econ), ]

corrW5W8_complete_econ <- cor.test(x=df_GLES17_correlation_Subset_econ$EcoPercSocio_W5, 
                                   y=df_GLES17_correlation_Subset_econ$EcoPercSocio_W8, method = 'pearson', exact = FALSE)
corrW5W13_complete_econ <- cor.test(x=df_GLES17_correlation_Subset_econ$EcoPercSocio_W5, 
                                    y=df_GLES17_correlation_Subset_econ$EcoPercSocio_W13, method = 'pearson', exact = FALSE)
corrW5W14_complete_econ <- cor.test(x=df_GLES17_correlation_Subset_econ$EcoPercSocio_W5, 
                                    y=df_GLES17_correlation_Subset_econ$EcoPercSocio_W14, method = 'pearson', exact = FALSE)
corrW5W15_complete_econ <- cor.test(x=df_GLES17_correlation_Subset_econ$EcoPercSocio_W5,
                                    y=df_GLES17_correlation_Subset_econ$EcoPercSocio_W15, method = 'pearson', exact = FALSE)

#### <<<>>> Step 4: Run correlation for Government Satisfaction ####

# Generate subset of respondents for whom there is valid data in each of the six categorization varibles:
subset_correlation_govsat <- c("lfdn", "GovSat_W5", "GovSat_W8", 
                               "GovSat_W13", "GovSat_W14",
                               "GovSat_W15")
df_GLES17_correlation_Subset_govsat <- df_GLES17[subset_correlation_govsat]
df_GLES17_correlation_Subset_govsat <- df_GLES17_correlation_Subset_govsat[complete.cases(df_GLES17_correlation_Subset_govsat), ]

corrW5W8_complete_govsat <- cor.test(x=df_GLES17_correlation_Subset_govsat$GovSat_W5, 
                                     y=df_GLES17_correlation_Subset_govsat$GovSat_W8, method = 'pearson', exact = FALSE)
corrW5W13_complete_govsat <- cor.test(x=df_GLES17_correlation_Subset_govsat$GovSat_W5, 
                                      y=df_GLES17_correlation_Subset_govsat$GovSat_W13, method = 'pearson', exact = FALSE)
corrW5W14_complete_govsat <- cor.test(x=df_GLES17_correlation_Subset_govsat$GovSat_W5, 
                                      y=df_GLES17_correlation_Subset_govsat$GovSat_W14, method = 'pearson', exact = FALSE)
corrW5W15_complete_govsat <- cor.test(x=df_GLES17_correlation_Subset_govsat$GovSat_W5,
                                      y=df_GLES17_correlation_Subset_govsat$GovSat_W15, method = 'pearson', exact = FALSE)

#### <<<>>> Step 5: Run correlation for Climate Change Attitudes ####

# Generate subset of respondents for whom there is valid data in each of the six categorization varibles:
subset_correlation_climate <- c("lfdn", "ClimateChange_W4", "ClimateChange_W8", 
                                "ClimateChange_W13", "ClimateChange_W14",
                                "ClimateChange_W15")
df_GLES17_correlation_Subset_climate <- df_GLES17[subset_correlation_climate]
df_GLES17_correlation_Subset_climate <- df_GLES17_correlation_Subset_climate[complete.cases(df_GLES17_correlation_Subset_climate), ]

corrW5W8_complete_climate <- cor.test(x=df_GLES17_correlation_Subset_climate$ClimateChange_W4, 
                                      y=df_GLES17_correlation_Subset_climate$ClimateChange_W8, method = 'pearson', exact = FALSE)
corrW5W13_complete_climate <- cor.test(x=df_GLES17_correlation_Subset_climate$ClimateChange_W4, 
                                       y=df_GLES17_correlation_Subset_climate$ClimateChange_W13, method = 'pearson', exact = FALSE)
corrW5W14_complete_climate <- cor.test(x=df_GLES17_correlation_Subset_climate$ClimateChange_W4, 
                                       y=df_GLES17_correlation_Subset_climate$ClimateChange_W14, method = 'pearson', exact = FALSE)
corrW5W15_complete_climate <- cor.test(x=df_GLES17_correlation_Subset_climate$ClimateChange_W4,
                                       y=df_GLES17_correlation_Subset_climate$ClimateChange_W15, method = 'pearson', exact = FALSE)

#### <<<>>> Step 6: Run correlation for Political Interest ####

# Generate subset of respondents for whom there is valid data in each of the six categorization varibles:
subset_correlation_polint <- c("lfdn", "PolInt_W5", "PolInt_W8", 
                               "PolInt_W9", "PolInt_W13", "PolInt_W14",
                               "PolInt_W15")
df_GLES17_correlation_Subset_polint <- df_GLES17[subset_correlation_polint]
df_GLES17_correlation_Subset_polint <- df_GLES17_correlation_Subset_polint[complete.cases(df_GLES17_correlation_Subset_polint), ]

corrW5W8_complete_polint <- cor.test(x=df_GLES17_correlation_Subset_polint$PolInt_W5, 
                                     y=df_GLES17_correlation_Subset_polint$PolInt_W8, method = 'pearson', exact = FALSE)
corrW5W9_complete_polint <- cor.test(x=df_GLES17_correlation_Subset_polint$PolInt_W5, 
                                     y=df_GLES17_correlation_Subset_polint$PolInt_W9, method = 'pearson', exact = FALSE)
corrW5W13_complete_polint <- cor.test(x=df_GLES17_correlation_Subset_polint$PolInt_W5, 
                                      y=df_GLES17_correlation_Subset_polint$PolInt_W13, method = 'pearson', exact = FALSE)
corrW5W14_complete_polint <- cor.test(x=df_GLES17_correlation_Subset_polint$PolInt_W5, 
                                      y=df_GLES17_correlation_Subset_polint$PolInt_W14, method = 'pearson', exact = FALSE)
corrW5W15_complete_polint <- cor.test(x=df_GLES17_correlation_Subset_polint$PolInt_W5,
                                      y=df_GLES17_correlation_Subset_polint$PolInt_W15, method = 'pearson', exact = FALSE)


#### <<<>>> Step 9: Combine the correlation into a table and add confidence intervals ####

#### >>> Populism Correlations Partial
correlation_estimates_b <- c(corrW5W8$estimate, corrW5W9$estimate, corrW5W13$estimate, corrW5W14$estimate, corrW5W15$estimate)
correlation_estimates_b <- format(round(correlation_estimates_b, 3), nsmall = 3)
correlation_estimates_b <- as.data.frame(correlation_estimates_b)

#### >>> Populism Correlations (Complete - minimum score)
correlation_estimates_complete_b <- c(corrW5W8_complete_b$estimate, corrW5W9_complete_b$estimate, corrW5W13_complete_b$estimate,
                                      corrW5W14_complete_b$estimate, corrW5W15_complete_b$estimate)
correlation_estimates_complete_b <- format(round(correlation_estimates_complete_b, 3), nsmall = 3)
df_correlation_estimates_complete_b <- as.data.frame(correlation_estimates_complete_b)
df_correlation_estimates_complete_b$correlation <- as.numeric(df_correlation_estimates_complete_b$correlation_estimates_complete_b)

## add confidence interval for complete data (Fisher Transformation)
df_correlation_estimates_complete_b$Upper <- tanh(atanh(df_correlation_estimates_complete_b$correlation)+1*qnorm(.68)*(1/sqrt(5333)))
df_correlation_estimates_complete_b$Lower <- tanh(atanh(df_correlation_estimates_complete_b$correlation)+(-1)*qnorm(.68)*(1/sqrt(5333)))

# Add time variable (in years)
df_correlation_estimates_complete_b$time <- c(0.08333333, 0.5, 2.666667, 3.166667, 3.583333)
# drop first variable:
df_correlation_estimates_complete_b <- df_correlation_estimates_complete_b[-1]

#### >>> Populism Correlations (Complete - multiplied)
correlation_estimates_complete_b_mult <- c(corrW5W8_complete_b_mult$estimate, corrW5W9_complete_b_mult$estimate, corrW5W13_complete_b_mult$estimate,
                                           corrW5W14_complete_b_mult$estimate, corrW5W15_complete_b_mult$estimate)
correlation_estimates_complete_b_mult <- format(round(correlation_estimates_complete_b_mult, 3), nsmall = 3)
df_correlation_estimates_complete_b_mult <- as.data.frame(correlation_estimates_complete_b_mult)
df_correlation_estimates_complete_b_mult$correlation <- as.numeric(df_correlation_estimates_complete_b_mult$correlation_estimates_complete_b_mult)

## add confidence interval for complete data (Fisher Transformation)
df_correlation_estimates_complete_b_mult$Upper <- tanh(atanh(df_correlation_estimates_complete_b_mult$correlation)+1*qnorm(.68)*(1/sqrt(5333)))
df_correlation_estimates_complete_b_mult$Lower <- tanh(atanh(df_correlation_estimates_complete_b_mult$correlation)+(-1)*qnorm(.68)*(1/sqrt(5333)))

# Add time variable (in years)
df_correlation_estimates_complete_b_mult$time <- c(0.08333333, 0.5, 2.666667, 3.166667, 3.583333)
# drop first variable:
df_correlation_estimates_complete_b_mult <- df_correlation_estimates_complete_b_mult[-1]


#### >>> Populism Correlations (Complete - 2 DImensional Minimum score)
correlation_estimates_complete_c_twodim <- c(corrW5W8_complete_c_twodim$estimate, corrW5W9_complete_c_twodim$estimate, corrW5W13_complete_c_twodim$estimate,
                                             corrW5W14_complete_c_twodim$estimate, corrW5W15_complete_c_twodim$estimate)
correlation_estimates_complete_c_twodim <- format(round(correlation_estimates_complete_c_twodim, 3), nsmall = 3)
df_correlation_estimates_complete_c_twodim <- as.data.frame(correlation_estimates_complete_c_twodim)
df_correlation_estimates_complete_c_twodim$correlation <- as.numeric(df_correlation_estimates_complete_c_twodim$correlation_estimates_complete_c_twodim)

## add confidence interval for complete data (Fisher Transformation)
df_correlation_estimates_complete_c_twodim$Upper <- tanh(atanh(df_correlation_estimates_complete_c_twodim$correlation)+1*qnorm(.68)*(1/sqrt(5333)))
df_correlation_estimates_complete_c_twodim$Lower <- tanh(atanh(df_correlation_estimates_complete_c_twodim$correlation)+(-1)*qnorm(.68)*(1/sqrt(5333)))

# Add time variable (in years)
df_correlation_estimates_complete_c_twodim$time <- c(0.08333333, 0.5, 2.666667, 3.166667, 3.583333)
# drop first variable:
df_correlation_estimates_complete_c_twodim <- df_correlation_estimates_complete_c_twodim[-1]


#### >>> Econ Evaluation
correlation_estimates_econ <- c(corrW5W8_complete_econ$estimate, NA, corrW5W13_complete_econ$estimate, 
                                corrW5W14_complete_econ$estimate, corrW5W15_complete_econ$estimate)
correlation_estimates_econ <- format(round(correlation_estimates_econ, 3), nsmall = 3)
df_correlation_estimates_econ <- as.data.frame(correlation_estimates_econ)
df_correlation_estimates_econ$correlation <- as.numeric(df_correlation_estimates_econ$correlation_estimates_econ)

## add confidence interval for complete data (Fisher Transformation)
df_correlation_estimates_econ$Upper <- tanh(atanh(df_correlation_estimates_econ$correlation)+1*qnorm(.68)*(1/sqrt(6378)))
df_correlation_estimates_econ$Lower <- tanh(atanh(df_correlation_estimates_econ$correlation)+(-1)*qnorm(.68)*(1/sqrt(6378)))

# Add time variable (in years)
df_correlation_estimates_econ$time <- c(0.08333333, NA, 2.666667, 3.166667, 3.583333)
# drop first variable:
df_correlation_estimates_econ <- df_correlation_estimates_econ[-1]


#### >>> Government Performance
correlation_estimates_gov <- c(corrW5W8_complete_govsat$estimate, NA, corrW5W13_complete_govsat$estimate, 
                               corrW5W14_complete_govsat$estimate, corrW5W15_complete_govsat$estimate)
correlation_estimates_gov <- format(round(correlation_estimates_gov, 3), nsmall = 3)
df_correlation_estimates_gov <- as.data.frame(correlation_estimates_gov)
df_correlation_estimates_gov$correlation <- as.numeric(df_correlation_estimates_gov$correlation_estimates_gov)

## add confidence interval for complete data (Fisher Transformation)
df_correlation_estimates_gov$Upper <- tanh(atanh(df_correlation_estimates_gov$correlation)+1*qnorm(.68)*(1/sqrt(6423)))
df_correlation_estimates_gov$Lower <- tanh(atanh(df_correlation_estimates_gov$correlation)+(-1)*qnorm(.68)*(1/sqrt(6423)))

# Add time variable (in years)
df_correlation_estimates_gov$time <- c(0.08333333, NA, 2.666667, 3.166667, 3.583333)
# drop first variable:
df_correlation_estimates_gov <- df_correlation_estimates_gov[-1]

#### >>> Climate Change
correlation_estimates_climate <- c(corrW5W8_complete_climate$estimate, NA, corrW5W13_complete_climate$estimate, 
                                   corrW5W14_complete_climate$estimate, corrW5W15_complete_climate$estimate)
correlation_estimates_climate <- format(round(correlation_estimates_climate, 3), nsmall = 3)
df_correlation_estimates_climate <- as.data.frame(correlation_estimates_climate)
df_correlation_estimates_climate$correlation <- as.numeric(df_correlation_estimates_climate$correlation_estimates_climate)

## add confidence interval for complete data (Fisher Transformation)
df_correlation_estimates_climate$Upper <- tanh(atanh(df_correlation_estimates_climate$correlation)+1*qnorm(.68)*1/sqrt(6423))
df_correlation_estimates_climate$Lower <- tanh(atanh(df_correlation_estimates_climate$correlation)+(-1)*qnorm(.68)*1/sqrt(6423))

# Add time variable (in years)
df_correlation_estimates_climate$time <- c(0.1666667, NA, 2.75, 3.3333333, 3.6666667)
# drop first variable:
df_correlation_estimates_climate <- df_correlation_estimates_climate[-1]

#### >>> Political Interest
correlation_estimates_polint <- c(corrW5W8_complete_polint$estimate, corrW5W9_complete_polint$estimate, 
                                  corrW5W13_complete_polint$estimate, 
                                  corrW5W14_complete_polint$estimate, corrW5W15_complete_polint$estimate)
correlation_estimates_polint <- format(round(correlation_estimates_polint, 3), nsmall = 3)
df_correlation_estimates_polint <- as.data.frame(correlation_estimates_polint)
df_correlation_estimates_polint$correlation <- as.numeric(df_correlation_estimates_polint$correlation_estimates_polint)

## add confidence interval for complete data (Fisher Transformation)
df_correlation_estimates_polint$Upper <- tanh(atanh(df_correlation_estimates_polint$correlation)+1*qnorm(.68)*1/sqrt(6423))
df_correlation_estimates_polint$Lower <- tanh(atanh(df_correlation_estimates_polint$correlation)+(-1)*qnorm(.68)*1/sqrt(6423))

# Add time variable (in years)
df_correlation_estimates_polint$time <- c(0.08333333, 0.5, 2.666667, 3.166667, 3.583333)
# drop first variable:
df_correlation_estimates_polint <- df_correlation_estimates_polint[-1]

# single dataframe
correlation_table_b <- as.data.frame(rbind(df_correlation_estimates_complete_b,
                                           #df_correlation_estimates_complete_b_mult,
                                           df_correlation_estimates_polint,
                                           df_correlation_estimates_gov,
                                           df_correlation_estimates_econ, 
                                           df_correlation_estimates_climate))

# Add grouping variable (by variable)
correlation_table_b$Variable <- rep(c(1:5), each = 5)
correlation_table_b$Variable <- factor(correlation_table_b$Variable,
                                       levels = c(1:5),
                                       labels = c("Populism",
                                                  "Political Interest",
                                                  "Government \n Satisfaction",
                                                  "Economic \n Evaluation",
                                                  "Climate Change"))


##########################################################################################/
#### <<>> Figure 1 - Distribution of Populism Scores in Germany across Six Panel Waves ####
#########################################################################################/

## Reshape Data Set for plotting purposes (into long format)
df_Long_PopScore <- melt(df_GLES17, id.vars = c("lfdn"), measure.vars = c("Populism_Goertz_AbsoluteMinimum_W5",
                                                                          "Populism_Goertz_AbsoluteMinimum_W8",
                                                                          "Populism_Goertz_AbsoluteMinimum_W9",
                                                                          "Populism_Goertz_AbsoluteMinimum_W13",
                                                                          "Populism_Goertz_AbsoluteMinimum_W14",
                                                                          "Populism_Goertz_AbsoluteMinimum_W15"),
                         variable.name = "PanelWave", value.name = "PopulismScore")
## Add Level for Panel Wave Variable
levels(df_Long_PopScore$PanelWave) <- c("August '17",
                                        "September/\nOctober '17",
                                        "March '18",
                                        "April/May '20",
                                        "November '20",
                                        "February/March 2021")
# Plot
plot_Populism_Dist <-  df_Long_PopScore %>%
  ggplot(aes(y = PanelWave, group = PanelWave)) +
  geom_density_ridges(
    aes(x = PopulismScore), color="black", from = 0, to = 5,  alpha = .6,
    quantile_lines=T,
    quantile_fun=function(x,...)mean(x,na.rm = T),
    scale = 1) +
  coord_flip() +
  xlab("Populism Score") +
  ylab("GLES Panel Wave Time") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  ggtitle("")

#### >>> Safe Plot 

tiff("FIGURE1_Distribution_Populism_Scores.tiff",
     units="in", width=7.5, height=5, res=600, compression = "lzw")
plot_Populism_Dist
dev.off()

##############################################################################################/
#### <<>> Figure 2: Relative Stability: Statistic - Correlations (1st Wave-to-Other Waves) ####
##############################################################################################/

# Plot
correlation_Wave1_Others_plot <- ggplot(correlation_table_b, 
                                        aes(x=time, 
                                            y=correlation,
                                            shape = Variable,
                                            color=Variable )) +
  geom_point(aes(y=correlation), size=1.2) +
  geom_line(linetype="dashed", size = 0.25) +
  ylab("Correlation (Pearson's r)") +
  xlab("Time lapsed since first measurement (in years)") +
  theme_minimal() +
  theme(legend.position="bottom") + 
  scale_color_manual(values=c("Populism"="#000000",
                              "Political Interest"="#E69F00",
                              "Government \n Satisfaction"="#56B4E9",
                              "Economic \n Evaluation"="#009E73",
                              "Climate Change"="#F0E442")) + 
  base_breaks_x1(correlation_table_b$time) +
  base_breaks_y1(correlation_table_b$correlation)+
  guides(color=guide_legend(nrow=2,byrow=TRUE))


#### >>> Safe Plot

tiff("correlation_Wave1_Others_plot.tiff",
     units="in", width=6.5, height=4.5, res=600, compression = "lzw")
correlation_Wave1_Others_plot
dev.off()


######################################################################################/
#### <<>> Figure 3  - Absolute Stability & Comparison (Crossing Opinion Boundaries) ####
######################################################################################/

## Plot compares stable populist attitude holders , and "other" category plus 
## comparison to other constructs (political 
## interest, satisfaction with government, perceived economic situation and 
## position on environment vs economy). Analyses also include code for populism
## sub-dimensions included in the Appendix. Baseline is W5 for all variables but 
## environment variable baseline is W4 (global stability with incrementally
## increasing time spans)
## Note: The mid-point here is considered as indicating nuanced opinion/mid point
## between the two extremes/

#Summarize Data - W5W8
# Populism
tab_V2_a_pop <- df_GLES17 %>%
  select(starts_with("StablePop_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_V2_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=1) %>%
  rename(Category=StablePop_V2_W5W8)
# Political Interest
tab_V2_a_polint <- df_GLES17 %>%
  select(starts_with("StableInt_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StableInt_V2_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=2) %>%
  rename(Category=StableInt_V2_W5W8)
# Satisfaction with Government
tab_V2_a_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(complete.cases(.)) %>%
  count(StableGovSat_V2_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=3) %>%
  rename(Category=StableGovSat_V2_W5W8)
# Sociotropic Economic Perceptions
tab_V2_a_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(complete.cases(.)) %>%
  count(StableEcon_V2_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=4) %>%
  rename(Category=StableEcon_V2_W5W8)
# Environment vs Economy 
tab_V2_a_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(complete.cases(.)) %>%
  count(StableClimate_V2_W4W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=5) %>%
  rename(Category=StableClimate_V2_W4W8)

####Summarize Data - W5W9
#Populism
tab_V2_b_pop <- df_GLES17 %>%
  select(starts_with("StablePop_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_V2_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=1) %>%
  rename(Category=StablePop_V2_W5W9)
# Political Interest
tab_V2_b_polint <- df_GLES17 %>%
  select(starts_with("StableInt_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StableInt_V2_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=2) %>%
  rename(Category=StableInt_V2_W5W9)

# Satisfaction with Government (not available)
freq <- c(NA, NA, NA)
time <- c(2,2,2)
var <- c(3, 3, 3)
n <- c(NA, NA, NA)
Category <- c(1,2,3)

tab_V2_b_SatGov <- as.data.frame(cbind(Category, n, freq, time, var))

# Sociotropic Economic Perceptions (not available)
var <- c(4, 4, 4)
Category <- c(1,2,3)

tab_V2_b_EcoPercSocio <- as.data.frame(cbind(Category, n, freq, time, var))

# Environment vs Economy  (not available)
var <- c(5, 5, 5)
tab_V2_b_ClimateChange <- as.data.frame(cbind(Category, n, freq, time, var))

#Summarize Data - W5W13
#Populism
tab_V2_c_pop <- df_GLES17 %>%
  select(starts_with("StablePop_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_V2_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=1) %>%
  rename(Category=StablePop_V2_W5W13)
# Political Interest
tab_V2_c_polint <- df_GLES17 %>%
  select(starts_with("StableInt_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StableInt_V2_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=2) %>%
  rename(Category=StableInt_V2_W5W13)
# Satisfaction with Government
tab_V2_c_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(complete.cases(.)) %>%
  count(StableGovSat_V2_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=3) %>%
  rename(Category=StableGovSat_V2_W5W13)
# Sociotropic Economic Perceptions
tab_V2_c_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(complete.cases(.)) %>%
  count(StableEcon_V2_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=4) %>%
  rename(Category=StableEcon_V2_W5W13)
# Environment vs Economy 
tab_V2_c_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(complete.cases(.)) %>%
  count(StableClimate_V2_W4W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=5) %>%
  rename(Category=StableClimate_V2_W4W13)


#Summarize Data - W5W14
#Populism
tab_V2_d_pop <- df_GLES17 %>%
  select(starts_with("StablePop_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_V2_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=1) %>%
  rename(Category=StablePop_V2_W5W14)
# Political Interest
tab_V2_d_polint <- df_GLES17 %>%
  select(starts_with("StableInt_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StableInt_V2_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=2) %>%
  rename(Category=StableInt_V2_W5W14)
# Satisfaction with Government
tab_V2_d_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(complete.cases(.)) %>%
  count(StableGovSat_V2_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=3) %>%
  rename(Category=StableGovSat_V2_W5W14)
# Sociotropic Economic Perceptions
tab_V2_d_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(complete.cases(.)) %>%
  count(StableEcon_V2_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=4) %>%
  rename(Category=StableEcon_V2_W5W14)
# Environment vs Economy 
tab_V2_d_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(complete.cases(.)) %>%
  count(StableClimate_V2_W4W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=5) %>%
  rename(Category=StableClimate_V2_W4W14)

#Summarize Data - W5W15
#Populism
tab_V2_e_pop <- df_GLES17 %>%
  select(starts_with("StablePop_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_V2_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=1) %>%
  rename(Category=StablePop_V2_W5W15)
# Political Interest
tab_V2_e_polint <- df_GLES17 %>%
  select(starts_with("StableInt_V2_W")) %>%
  filter(complete.cases(.)) %>%
  count(StableInt_V2_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=2) %>%
  rename(Category=StableInt_V2_W5W15)
# Satisfaction with Government
tab_V2_e_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(complete.cases(.)) %>%
  count(StableGovSat_V2_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=3) %>%
  rename(Category=StableGovSat_V2_W5W15)
# Sociotropic Economic Perceptions
tab_V2_e_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(complete.cases(.)) %>%
  count(StableEcon_V2_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=4) %>%
  rename(Category=StableEcon_V2_W5W15)
# Environment vs Economy 
tab_V2_e_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(complete.cases(.)) %>%
  count(StableClimate_V2_W4W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=5) %>%
  rename(Category=StableClimate_V2_W4W15)

#Build dataset for plot:
df_stable_plot_V2 <- as.data.frame(rbind(tab_V2_a_pop, tab_V2_b_pop, tab_V2_c_pop, 
                                         tab_V2_d_pop, tab_V2_e_pop,
                                         tab_V2_a_polint, tab_V2_b_polint, tab_V2_c_polint,
                                         tab_V2_d_polint, tab_V2_e_polint,
                                         tab_V2_a_SatGov, tab_V2_b_SatGov, tab_V2_c_SatGov,
                                         tab_V2_d_SatGov, tab_V2_e_SatGov,
                                         tab_V2_a_EcoPercSocio, tab_V2_b_EcoPercSocio, tab_V2_c_EcoPercSocio,
                                         tab_V2_d_EcoPercSocio, tab_V2_e_EcoPercSocio,
                                         tab_V2_a_ClimateChange, tab_V2_b_ClimateChange, tab_V2_c_ClimateChange,
                                         tab_V2_d_ClimateChange, tab_V2_e_ClimateChange))
df_stable_plot_V2$freq <- round(df_stable_plot_V2$freq,2)

# Add time lapsed variable
df_stable_plot_V2$time_lapsed <- NA
df_stable_plot_V2$time_lapsed[df_stable_plot_V2$time==1] <- 0.08333333
df_stable_plot_V2$time_lapsed[df_stable_plot_V2$time==2] <- 0.5
df_stable_plot_V2$time_lapsed[df_stable_plot_V2$time==3] <- 2.666667
df_stable_plot_V2$time_lapsed[df_stable_plot_V2$time==4] <- 3.166667
df_stable_plot_V2$time_lapsed[df_stable_plot_V2$time==5] <- 3.583333

#Add value labels:
df_stable_plot_V2$Category <- factor(df_stable_plot_V2$Category,
                                     labels=c("Unstable", "Stable \n Positive",
                                              "Stable \n Negative", "Middle"))
df_stable_plot_V2$time <- factor(df_stable_plot_V2$time,
                                 labels=c("1", "2",
                                          "3", "4",
                                          "5"))
df_stable_plot_V2$var <- factor(df_stable_plot_V2$var,
                                labels=c("Populism", "Political \n Interest", 
                                         "Satisfaction \n with Government",
                                         "Economic \n Perceptions",
                                         "Climate \n Change"))


#### <<<>>> Step 2: plot

# plot
plot_desc_overtime_pop <- df_stable_plot_V2%>%
  filter(!is.na(freq) & Category=="Unstable") %>%
  ggplot(., aes(x=time_lapsed, y=freq, colour=var, shape=var, group=var)) +
  geom_point(size=2) +
  geom_line() + 
  scale_color_manual(values=c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442")) +
  base_breaks_x3(df_stable_plot_V2$time_lapsed) +
  base_breaks_y3(df_stable_plot_V2$freq) +
  scale_y_continuous(labels=scales::percent) +
  theme_minimal() +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  xlab("") +
  ylab("Percent") +
  xlab("Time since first measurement (years)") +
  guides(color=guide_legend(nrow=1, byrow=TRUE)) 


#### Safe Plot

tiff("FIGURE3_Pop_Over_Time_Desc.tiff",
     units="in", width=8, height=6, res=900, compression = "lzw")
plot_desc_overtime_pop
dev.off()

################################################################################/
#### <<>> Table 2 Switch Count                                               ####
################################################################################/

#neither agree nor disagree=nuanced opinion
round(prop.table(table(df_GLES17$switch.count))*100,2)

################################################################################/
#### <<>> Table 3 - Within Respondents Absolute Differences and Sd           ####
################################################################################/

## Create table that includes the average absolute change between subsequent
## panel waves and the average standard deviation of the absolute change
## between subsequent panel waves for all relevant constructs:

df_abs_analysis <- as.data.frame(cbind(c("Concept",
                                         "Populist Attitudes",
                                         "Populist Attitudes (cat)",
                                         "Political Interest",
                                         "Satisfaction with Government",
                                         "Economic Perceptions",
                                         "Climate Change",
                                         "Anti-Elitism",
                                         "Homogeneity",
                                         "Sovereignty"),
                                       # mean absolute change (W5-W8; W4-W8 for climate change)
                                       rbind("Mean_abs_Change_W5W8",
                                             round(mean(df_GLES17$Pop_W5_W8_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$Pop_W5_W8_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$PolInt_W5_W8_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$GovSat_W5_W8_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$EcoPercSocio_W5_W8_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$ClimateChange_W5_W8_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(mean(df_GLES17$AE_W5_W8_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$HO_W5_W8_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$SO_W5_W8_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # sd absolute change (W5-W8; W4-W8 for climate change)
                                       rbind("Sd_abs_Change_W5W8",
                                             round(sd(df_GLES17$Pop_W5_W8_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$Pop_W5_W8_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$PolInt_W5_W8_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$GovSat_W5_W8_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$EcoPercSocio_W5_W8_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$ClimateChange_W5_W8_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(sd(df_GLES17$AE_W5_W8_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$HO_W5_W8_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$SO_W5_W8_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # mean absolute change (W8-W9)
                                       rbind("Mean_abs_Change_W8W9",
                                             round(mean(df_GLES17$Pop_W8_W9_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$Pop_W8_W9_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$PolInt_W8_W9_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$GovSat_W8_W9_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$EcoPercSocio_W8_W9_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$ClimateChange_W8_W9_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(mean(df_GLES17$AE_W8_W9_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$HO_W8_W9_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$SO_W8_W9_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # sd absolute change (W8-W9)
                                       rbind("Sd_abs_Change_W8W9",
                                             round(sd(df_GLES17$Pop_W8_W9_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$Pop_W8_W9_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$PolInt_W8_W9_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$GovSat_W8_W9_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$EcoPercSocio_W8_W9_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$ClimateChange_W8_W9_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(sd(df_GLES17$AE_W8_W9_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$HO_W8_W9_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$SO_W8_W9_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # mean absolute change (W9-W13; 8-13 for climate change, ecoperc, and gov sat because
                                       #                       W9 measure not available)
                                       rbind("Mean_abs_Change_W9W13",
                                             round(mean(df_GLES17$Pop_W9_W13_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$Pop_W9_W13_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$PolInt_W9_W13_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$GovSat_W8_W13_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$EcoPercSocio_W8_W13_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$ClimateChange_W8_W13_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(mean(df_GLES17$AE_W9_W13_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$HO_W9_W13_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$SO_W9_W13_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # sd absolute change (W9-W13; 8-13 for climate change, ecoperc, and gov sat because
                                       #                       W9 measure not available)
                                       rbind("Sd_abs_Change_W9W13",
                                             round(sd(df_GLES17$Pop_W9_W13_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$Pop_W9_W13_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$PolInt_W9_W13_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$GovSat_W8_W13_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$EcoPercSocio_W8_W13_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$ClimateChange_W8_W13_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(sd(df_GLES17$AE_W9_W13_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$HO_W9_W13_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$SO_W9_W13_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # mean absolute change (W13-W14)
                                       rbind("Mean_abs_Change_W13W14",
                                             round(mean(df_GLES17$Pop_W13_W14_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$Pop_W13_W14_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$PolInt_W13_W14_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$GovSat_W13_W14_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$EcoPercSocio_W13_W14_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$ClimateChange_W13_W14_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(mean(df_GLES17$AE_W13_W14_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$HO_W13_W14_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$SO_W13_W14_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # sd absolute change (W13-W14)
                                       rbind("Sd_abs_Change_W13W14",
                                             round(sd(df_GLES17$Pop_W13_W14_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$Pop_W13_W14_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$PolInt_W13_W14_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$GovSat_W13_W14_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$EcoPercSocio_W13_W14_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$ClimateChange_W13_W14_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(sd(df_GLES17$AE_W13_W14_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$HO_W13_W14_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$SO_W13_W14_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # mean absolute change (W14-W15)
                                       rbind("Mean_abs_Change_W14W15",
                                             round(mean(df_GLES17$Pop_W14_W15_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$Pop_W14_W15_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$PolInt_W14_W15_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$GovSat_W14_W15_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$EcoPercSocio_W14_W15_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$ClimateChange_W14_W15_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(mean(df_GLES17$AE_W14_W15_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$HO_W14_W15_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$SO_W14_W15_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # sd absolute change (W14-W15)
                                       rbind("Sd_abs_Change_W14W15",
                                             round(sd(df_GLES17$Pop_W14_W15_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$Pop_W14_W15_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$PolInt_W14_W15_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$GovSat_W14_W15_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$EcoPercSocio_W14_W15_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$ClimateChange_W14_W15_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(sd(df_GLES17$AE_W14_W15_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$HO_W14_W15_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$SO_W14_W15_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # mean absolute change (Average across set of panel waves)
                                       rbind("Mean_Abs_Change",
                                             round(mean(df_GLES17$Pop_W5_W15_Av_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$Pop_W5_W15_Av_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$PolInt_W5_W15_Av_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$GovSat_W5_W15_Av_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$EcoPercSocio_W5_W15_Av_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$ClimateChange_W5_W15_Av_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(mean(df_GLES17$AE_W5_W15_Av_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$HO_W5_W15_Av_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(mean(df_GLES17$SO_W5_W15_Av_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2)),
                                       # SDs (absolute changes; Average across set of panel waves)
                                       rbind("SD_Abs_Change",
                                             round(sd(df_GLES17$Pop_W5_W15_Av_Abs[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$Pop_W5_W15_Av_Abs_cat[!is.na(df_GLES17$StablePop_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$PolInt_W5_W15_Av_Abs[!is.na(df_GLES17$StableInt_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$GovSat_W5_W15_Av_Abs[!is.na(df_GLES17$StableGovSat_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$EcoPercSocio_W5_W15_Av_Abs[!is.na(df_GLES17$StableEcon_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$ClimateChange_W5_W15_Av_Abs[!is.na(df_GLES17$StableClimate_W4W15)], na.rm=T),2),
                                             round(sd(df_GLES17$AE_W5_W15_Av_Abs[!is.na(df_GLES17$StableAntiElite_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$HO_W5_W15_Av_Abs[!is.na(df_GLES17$Stable_Homogeneity_W5W15)], na.rm=T),2),
                                             round(sd(df_GLES17$SO_W5_W15_Av_Abs[!is.na(df_GLES17$Stable_PeopleSov_W5W15)], na.rm=T),2))
)
)
#First row contains variable names:
names(df_abs_analysis) <- df_abs_analysis[1, ]
df_abs_analysis <- df_abs_analysis[-1, ]
df_abs_analysis



################################################################################################################/
#### <<>> Figure 4 - Correlation with Democratic Attitudes by Stability                                      ####
################################################################################################################/

## Estimate correlation with three democratic attitudes measured in Wave 15:
# 1. every party should have the chance to become part of the government (variable name: DemAtt_IT1_WX)
# 2. everyone should have the right to stand up for their opinion even if the majority has a different opinion (variable name: DemAtt_IT2_WX)
# 3. a vibrant democracy is unthinkable without an opposition (variable name: DemAtt_IT3_WX)
#
# Correlation altogether (with populist attitudes measured in waves 14 and 15) and then
# repeat step 1 but distinguish stable and non-stable populist.
# 
# Crete variable that combines stable non populists and stable populists into
# a single category resulting in:
# 1=unstable
# 2=stable (stable positive, negative and middle opinions)
df_GLES17$StablePop <- df_GLES17$StablePop_V2_W5W15
df_GLES17$StablePop[df_GLES17$StablePop_V2_W5W15>2] <- 2

## Correlation with no distinction (Wave 14 populist measures):
pop_dem_cor_IT1_W14 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, df_GLES17$DemAtt_IT1_W15, use = "complete")
pop_dem_cor_IT2_W14 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, df_GLES17$DemAtt_IT2_W15, use = "complete")
pop_dem_cor_IT3_W14 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, df_GLES17$DemAtt_IT3_W15, use = "complete")

## Correlation with no distinction (Wave 15 populist measures):
pop_dem_cor_IT1_W15 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, df_GLES17$DemAtt_IT1_W15, use = "complete")
pop_dem_cor_IT2_W15 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, df_GLES17$DemAtt_IT2_W15, use = "complete")
pop_dem_cor_IT3_W15 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, df_GLES17$DemAtt_IT3_W15, use = "complete")

## Correlation - stable populists (Wave 14 populist measures):
pop_dem_cor_IT1_W14_stab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop==2], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop==2], use = "complete")
pop_dem_cor_IT2_W14_stab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop==2], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop==2], use = "complete")
pop_dem_cor_IT3_W14_stab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop==2], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop==2], use = "complete")

## Correlation - unstable populists (Wave 14 populist measures):
pop_dem_cor_IT1_W14_unstab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop==1], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop==1], use = "complete")
pop_dem_cor_IT2_W14_unstab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop==1], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop==1], use = "complete")
pop_dem_cor_IT3_W14_unstab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop==1], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop==1], use = "complete")


## Correlation - stable populists (Wave 15 populist measures):
pop_dem_cor_IT1_W15_stab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop==2], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop==2], use = "complete")
pop_dem_cor_IT2_W15_stab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop==2], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop==2], use = "complete")
pop_dem_cor_IT3_W15_stab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop==2], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop==2], use = "complete")


## Correlation - unstable populists (Wave 15 populist measures):
pop_dem_cor_IT1_W15_unstab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop==1], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop==1], use = "complete")
pop_dem_cor_IT2_W15_unstab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop==1], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop==1], use = "complete")
pop_dem_cor_IT3_W15_unstab <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop==1], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop==1], use = "complete")

# Build dataframe for plotting:
# Variables: Wave, Combined/Stable/Unstable, Cor_Variable, Correlation, CI_Low, CI_Upper
df_cor_plot <- as.data.frame(rbind(c(1, 1, 1, pop_dem_cor_IT1_W14$estimate, pop_dem_cor_IT1_W14$conf.int[1], pop_dem_cor_IT1_W14$conf.int[2]),
                                   c(1, 1, 2, pop_dem_cor_IT2_W14$estimate, pop_dem_cor_IT2_W14$conf.int[1], pop_dem_cor_IT2_W14$conf.int[2]),
                                   c(1, 1, 3, pop_dem_cor_IT3_W14$estimate, pop_dem_cor_IT3_W14$conf.int[1], pop_dem_cor_IT3_W14$conf.int[2]),
                                   c(2, 1, 1, pop_dem_cor_IT1_W15$estimate, pop_dem_cor_IT1_W15$conf.int[1], pop_dem_cor_IT1_W15$conf.int[2]),
                                   c(2, 1, 2, pop_dem_cor_IT2_W15$estimate, pop_dem_cor_IT2_W15$conf.int[1], pop_dem_cor_IT2_W15$conf.int[2]),
                                   c(2, 1, 3, pop_dem_cor_IT3_W15$estimate, pop_dem_cor_IT3_W15$conf.int[1], pop_dem_cor_IT3_W15$conf.int[2]),
                                   c(1, 2, 1, pop_dem_cor_IT1_W14_stab$estimate, pop_dem_cor_IT1_W14_stab$conf.int[1], pop_dem_cor_IT1_W14_stab$conf.int[2]),
                                   c(1, 2, 2, pop_dem_cor_IT2_W14_stab$estimate, pop_dem_cor_IT2_W14_stab$conf.int[1], pop_dem_cor_IT2_W14_stab$conf.int[2]),
                                   c(1, 2, 3, pop_dem_cor_IT3_W14_stab$estimate, pop_dem_cor_IT3_W14_stab$conf.int[1], pop_dem_cor_IT3_W14_stab$conf.int[2]),
                                   c(2, 2, 1, pop_dem_cor_IT1_W15_stab$estimate, pop_dem_cor_IT1_W15_stab$conf.int[1], pop_dem_cor_IT1_W15_stab$conf.int[2]),
                                   c(2, 2, 2, pop_dem_cor_IT2_W15_stab$estimate, pop_dem_cor_IT2_W15_stab$conf.int[1], pop_dem_cor_IT2_W15_stab$conf.int[2]),
                                   c(2, 2, 3, pop_dem_cor_IT3_W15_stab$estimate, pop_dem_cor_IT3_W15_stab$conf.int[1], pop_dem_cor_IT3_W15_stab$conf.int[2]),
                                   c(1, 3, 1, pop_dem_cor_IT1_W14_unstab$estimate, pop_dem_cor_IT1_W14_unstab$conf.int[1], pop_dem_cor_IT1_W14_unstab$conf.int[2]),
                                   c(1, 3, 2, pop_dem_cor_IT2_W14_unstab$estimate, pop_dem_cor_IT2_W14_unstab$conf.int[1], pop_dem_cor_IT2_W14_unstab$conf.int[2]),
                                   c(1, 3, 3, pop_dem_cor_IT3_W14_unstab$estimate, pop_dem_cor_IT3_W14_unstab$conf.int[1], pop_dem_cor_IT3_W14_unstab$conf.int[2]),
                                   c(2, 3, 1, pop_dem_cor_IT1_W15_unstab$estimate, pop_dem_cor_IT1_W15_unstab$conf.int[1], pop_dem_cor_IT1_W15_unstab$conf.int[2]),
                                   c(2, 3, 2, pop_dem_cor_IT2_W15_unstab$estimate, pop_dem_cor_IT2_W15_unstab$conf.int[1], pop_dem_cor_IT2_W15_unstab$conf.int[2]),
                                   c(2, 3, 3, pop_dem_cor_IT3_W15_unstab$estimate, pop_dem_cor_IT3_W15_unstab$conf.int[1], pop_dem_cor_IT3_W15_unstab$conf.int[2])
))
names(df_cor_plot)[1] <- "Wave" #Panel Wave from which populist attitudes are taken
names(df_cor_plot)[2] <- "Distinction"
names(df_cor_plot)[3] <- "Cor_Variable"
names(df_cor_plot)[4] <- "Correlation"
names(df_cor_plot)[5] <- "CI_Low"
names(df_cor_plot)[6] <- "CI_Upper"
# Add labels for variables:
df_cor_plot$Wave <- as.factor(df_cor_plot$Wave)
levels(df_cor_plot$Wave) <- c("W5", "W6") 
#df_cor_plot$Distinction <- as.factor(df_cor_plot$Distinction)
#levels(df_cor_plot$Distinction) <- c("Combined", "Stable", "Unstable")
df_cor_plot$Cor_Variable <- as.factor(df_cor_plot$Cor_Variable)
levels(df_cor_plot$Cor_Variable) <- c("Every party should have \n the chance to become part \n of the government.",
                                      "Everyone should have the \n right to stand up for their \n opinion even if the  \n majority has a different opinion", 
                                      "A vibrant democracy is \n unthinkable without an opposition.")

## Plot
df_test_cor_plot <- df_cor_plot %>%
  filter(Wave=="W6") %>%
  ggplot(.,
         aes(x=Distinction, y=Correlation, color = as.factor(Distinction))) + 
  geom_pointrange(aes(ymin=CI_Low, ymax=CI_Upper), size=0.7) +
  geom_hline(yintercept=0, color='red', size=0.5)+
  facet_wrap( ~ Cor_Variable)+
  coord_flip()+
  xlab("")+
  theme_minimal() +
  base_breaks_x1(df_cor_plot$Distinction) +
  base_breaks_y1(df_cor_plot$Correlation) +
  theme(legend.position="bottom") +
  ylim(-0.3, 0.15) +
  scale_color_manual(values=c("#000000", "#E69F00", "#56B4E9")) +
  theme(legend.position = "none")+ 
  scale_x_continuous(breaks=c(1,2,3),
                     labels = c("Combined", 
                                "Stable only", 
                                "Unstable only"))

#### Safe Plot

tiff("FIGURE_5_Corellation_Democratic_Attitudes.tiff",
     units="in", width=8, height=4.5, res=900, compression = "lzw")
df_test_cor_plot
dev.off()


#################################################################################################################/
#### <<>> Table 4 - Populist Attitudes and Vote Choice                                                      ####
################################################################################################################/

## Objective is to identify any potential differences between stable and unstable
## populist attitude holders.

## Dichotomize List Vote:
df_GLES17$Dummy_PopVote <- NA
df_GLES17$Dummy_PopVote <- ifelse(df_GLES17$Vote_List_W58==6,1,0)

## Three category List Vote (0=mainstream, 1=AfD, 2=DieLinke):
df_GLES17$Three_PopVote <- NA
df_GLES17$Three_PopVote[df_GLES17$Vote_List_W58!=5 & df_GLES17$Vote_List_W58!=6] <- 0 #Mainstream
df_GLES17$Three_PopVote[df_GLES17$Vote_List_W58==6] <- 1 #AfD
df_GLES17$Three_PopVote[df_GLES17$Vote_List_W58==5] <- 2 #DieLinke

## Dichotomize above or below mean for absolute distance
df_GLES17$Dummy_AbsPopDistance <- NA
df_GLES17$Dummy_AbsPopDistance <- ifelse(df_GLES17$Pop_W5_W15_Av_Abs<mean(df_GLES17$Pop_W5_W15_Av_Abs, na.rm=T),
                                         0,1)

#### <<<>>> Analysis for maintext - All parties vs AfD - Dichotomized ####

# Dummy for stable and unstable (1=stable, 0=unstable)
df_GLES17$popstable_dummy <- ifelse(df_GLES17$StablePop_V2_W5W15>1,1,0)
df_GLES17$popstable_dummy[is.na(df_GLES17$StablePop_V2_W5W15)] <- NA

# Summarize (by stable and unstable)
df_GLES17 %>%
  filter(!is.na(Dummy_PopVote) & !is.na(Populism_Cat_V2_W5) & !is.na(StablePop_V2_W5W15)) %>%
  group_by(Populism_Cat_V2_W5, popstable_dummy) %>%
  count(Dummy_PopVote) %>%
  mutate(freq = round(n/sum(n),2))
#relevant here are rows 2, 4, 10, and 12

# Summarize (combined)
df_GLES17 %>%
  filter(!is.na(Dummy_PopVote) & !is.na(Populism_Cat_V2_W5) & !is.na(StablePop_V2_W5W15)) %>%
  group_by(Populism_Cat_V2_W5) %>%
  count(Dummy_PopVote) %>%
  mutate(freq = round(n/sum(n),2))
#relevant here are rows 2 and 6

################################################################################/
#### /// APPENDIX                                                           ####
################################################################################/


################################################################################/
#### <<>> APPENDIX 1 - Table A1.2 Descriptive Statistics for Appendix      ####
################################################################################/

#### <<<>>> Populist Attitudes ####

#### Wave 1:
prop.table(table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, useNA = "always"))
mean(df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, na.rm = T)
sd(df_GLES17$Populism_Goertz_AbsoluteMinimum_W5, na.rm = T)

#### Wave 2:
table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W8, useNA = "always")
prop.table(table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W8, useNA = "always"))
mean(df_GLES17$Populism_Goertz_AbsoluteMinimum_W8, na.rm = T)
sd(df_GLES17$Populism_Goertz_AbsoluteMinimum_W8, na.rm = T)

#### Wave 3:
table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W9, useNA = "always")
nrow(df_GLES17)-10871 
prop.table(table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W9, useNA = "always"))
mean(df_GLES17$Populism_Goertz_AbsoluteMinimum_W9, na.rm = T)
sd(df_GLES17$Populism_Goertz_AbsoluteMinimum_W9, na.rm = T)

#### Wave 4:
table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W13, useNA = "always")
nrow(df_GLES17)-13321 
prop.table(table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W13, useNA = "always"))
mean(df_GLES17$Populism_Goertz_AbsoluteMinimum_W13, na.rm = T)
sd(df_GLES17$Populism_Goertz_AbsoluteMinimum_W13, na.rm = T)

#### Wave 5:
table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, useNA = "always")
nrow(df_GLES17)-14231 
prop.table(table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, useNA = "always"))
mean(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, na.rm = T)
sd(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14, na.rm = T)

#### Wave 6:
table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, useNA = "always")
nrow(df_GLES17)- 14220  
prop.table(table(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, useNA = "always"))
mean(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, na.rm = T)
sd(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15, na.rm = T)

## n of respondents with valid answer in all six waves
desc_pop_subset <- c("Populism_Goertz_AbsoluteMinimum_W5",
                "Populism_Goertz_AbsoluteMinimum_W8", 
                "Populism_Goertz_AbsoluteMinimum_W9",
                "Populism_Goertz_AbsoluteMinimum_W13", 
                "Populism_Goertz_AbsoluteMinimum_W14",
                "Populism_Goertz_AbsoluteMinimum_W15")

df_GLES17_descpop <- df_GLES17[desc_pop_subset]
df_GLES17_descpop <- df_GLES17_descpop[complete.cases(df_GLES17_descpop), ]
nrow(df_GLES17_descpop)

#### <<<>>> Political Interest ####

#### Wave 1:
table(df_GLES17$PolInt_W5, useNA = "always")
nrow(df_GLES17)-8418 
prop.table(table(df_GLES17$PolInt_W5, useNA = "always"))
mean(df_GLES17$PolInt_W5, na.rm = T)
sd(df_GLES17$PolInt_W5, na.rm = T)

#### Wave 2:
table(df_GLES17$PolInt_W8, useNA = "always")
nrow(df_GLES17)-9171 
prop.table(table(df_GLES17$PolInt_W8, useNA = "always"))
mean(df_GLES17$PolInt_W8, na.rm = T)
sd(df_GLES17$PolInt_W8, na.rm = T)

#### Wave 3:
table(df_GLES17$PolInt_W9, useNA = "always")
nrow(df_GLES17)-10319  
prop.table(table(df_GLES17$PolInt_W9, useNA = "always"))
mean(df_GLES17$PolInt_W9, na.rm = T)
sd(df_GLES17$PolInt_W9, na.rm = T)

#### Wave 4:
table(df_GLES17$PolInt_W13, useNA = "always")
nrow(df_GLES17)-12991 
prop.table(table(df_GLES17$PolInt_W13, useNA = "always"))
mean(df_GLES17$PolInt_W13, na.rm = T)
sd(df_GLES17$PolInt_W13, na.rm = T)

#### Wave 5:
table(df_GLES17$PolInt_W14, useNA = "always")
nrow(df_GLES17)-13890 
prop.table(table(df_GLES17$PolInt_W14, useNA = "always"))
mean(df_GLES17$PolInt_W14, na.rm = T)
sd(df_GLES17$PolInt_W14, na.rm = T)

#### Wave 6:
table(df_GLES17$PolInt_W15, useNA = "always")
nrow(df_GLES17)- 13922   
prop.table(table(df_GLES17$PolInt_W15, useNA = "always"))
mean(df_GLES17$PolInt_W15, na.rm = T)
sd(df_GLES17$PolInt_W15, na.rm = T)

## n of respondents with valid answer in all six waves
desc_polint_subset <- c("PolInt_W5",
                     "PolInt_W8", 
                     "PolInt_W9",
                     "PolInt_W13", 
                     "PolInt_W14",
                     "PolInt_W15")

df_GLES17_descpolint <- df_GLES17[desc_polint_subset]
df_GLES17_descpolint <- df_GLES17_descpolint[complete.cases(df_GLES17_descpolint), ]
nrow(df_GLES17_descpolint)

#### <<<>>> Satisfaction with government performance ####

#### Wave 1:
table(df_GLES17$GovSat_W5, useNA = "always")
nrow(df_GLES17)-8483  
prop.table(table(df_GLES17$GovSat_W5, useNA = "always"))
mean(df_GLES17$GovSat_W5, na.rm = T)
sd(df_GLES17$GovSat_W5, na.rm = T)

#### Wave 2:
table(df_GLES17$GovSat_W8, useNA = "always")
nrow(df_GLES17)-9283 
prop.table(table(df_GLES17$GovSat_W8, useNA = "always"))
mean(df_GLES17$GovSat_W8, na.rm = T)
sd(df_GLES17$GovSat_W8, na.rm = T)

#### Wave 3:
table(df_GLES17$GovSat_W13, useNA = "always")
nrow(df_GLES17)-13038  
prop.table(table(df_GLES17$GovSat_W13, useNA = "always"))
mean(df_GLES17$GovSat_W13, na.rm = T)
sd(df_GLES17$GovSat_W13, na.rm = T)

#### Wave 4:
table(df_GLES17$GovSat_W14, useNA = "always")
nrow(df_GLES17)-13967 
prop.table(table(df_GLES17$GovSat_W14, useNA = "always"))
mean(df_GLES17$GovSat_W14, na.rm = T)
sd(df_GLES17$GovSat_W14, na.rm = T)

#### Wave 5:
table(df_GLES17$GovSat_W15, useNA = "always")
nrow(df_GLES17)- 13987   
prop.table(table(df_GLES17$GovSat_W15, useNA = "always"))
mean(df_GLES17$GovSat_W15, na.rm = T)
sd(df_GLES17$GovSat_W15, na.rm = T)

## n of respondents with valid answer in all six waves
desc_GovSat_subset <- c("GovSat_W5",
                        "GovSat_W8", 
                        "GovSat_W13", 
                        "GovSat_W14",
                        "GovSat_W15")

df_GLES17_descGovSat <- df_GLES17[desc_GovSat_subset]
df_GLES17_descGovSat <- df_GLES17_descGovSat[complete.cases(df_GLES17_descGovSat), ]
nrow(df_GLES17_descGovSat)

#### <<<>>> Perceived Economic Situation ####

#### Wave 1:
table(df_GLES17$EcoPercSocio_W5, useNA = "always")
nrow(df_GLES17)-8585  
prop.table(table(df_GLES17$EcoPercSocio_W5, useNA = "always"))
mean(df_GLES17$EcoPercSocio_W5, na.rm = T)
sd(df_GLES17$EcoPercSocio_W5, na.rm = T)

#### Wave 2:
table(df_GLES17$EcoPercSocio_W8, useNA = "always")
nrow(df_GLES17)-9306  
prop.table(table(df_GLES17$EcoPercSocio_W8, useNA = "always"))
mean(df_GLES17$EcoPercSocio_W8, na.rm = T)
sd(df_GLES17$EcoPercSocio_W8, na.rm = T)

#### Wave 3:
table(df_GLES17$EcoPercSocio_W13, useNA = "always")
nrow(df_GLES17)-13073   
prop.table(table(df_GLES17$EcoPercSocio_W13, useNA = "always"))
mean(df_GLES17$EcoPercSocio_W13, na.rm = T)
sd(df_GLES17$EcoPercSocio_W13, na.rm = T)

#### Wave 4:
table(df_GLES17$EcoPercSocio_W14, useNA = "always")
nrow(df_GLES17)-14005 
prop.table(table(df_GLES17$EcoPercSocio_W14, useNA = "always"))
mean(df_GLES17$EcoPercSocio_W14, na.rm = T)
sd(df_GLES17$EcoPercSocio_W14, na.rm = T)

#### Wave 5:
table(df_GLES17$EcoPercSocio_W15, useNA = "always")
nrow(df_GLES17)- 14011    
prop.table(table(df_GLES17$EcoPercSocio_W15, useNA = "always"))
mean(df_GLES17$EcoPercSocio_W15, na.rm = T)
sd(df_GLES17$EcoPercSocio_W15, na.rm = T)

## n of respondents with valid answer in all six waves
desc_EcoPercSocio_subset <- c("EcoPercSocio_W5",
                        "EcoPercSocio_W8", 
                        "EcoPercSocio_W13", 
                        "EcoPercSocio_W14",
                        "EcoPercSocio_W15")

df_GLES17_descEcoPercSocio <- df_GLES17[desc_EcoPercSocio_subset]
df_GLES17_descEcoPercSocio <- df_GLES17_descEcoPercSocio[complete.cases(df_GLES17_descEcoPercSocio), ]
nrow(df_GLES17_descEcoPercSocio)

#### <<<>>> Climate Change Protection ####

#### Wave 1:
table(df_GLES17$ClimateChange_W4, useNA = "always")
nrow(df_GLES17)-7614  
prop.table(table(df_GLES17$ClimateChange_W4, useNA = "always"))
mean(df_GLES17$ClimateChange_W4, na.rm = T)
sd(df_GLES17$ClimateChange_W4, na.rm = T)

#### Wave 2:
table(df_GLES17$ClimateChange_W8, useNA = "always")
nrow(df_GLES17)-9363  
prop.table(table(df_GLES17$ClimateChange_W8, useNA = "always"))
mean(df_GLES17$ClimateChange_W8, na.rm = T)
sd(df_GLES17$ClimateChange_W8, na.rm = T)

#### Wave 3:
table(df_GLES17$ClimateChange_W13, useNA = "always")
nrow(df_GLES17)-13111    
prop.table(table(df_GLES17$ClimateChange_W13, useNA = "always"))
mean(df_GLES17$ClimateChange_W13, na.rm = T)
sd(df_GLES17$ClimateChange_W13, na.rm = T)

#### Wave 4:
table(df_GLES17$ClimateChange_W14, useNA = "always")
nrow(df_GLES17)-14049 
prop.table(table(df_GLES17$ClimateChange_W14, useNA = "always"))
mean(df_GLES17$ClimateChange_W14, na.rm = T)
sd(df_GLES17$ClimateChange_W14, na.rm = T)

#### Wave 5:
table(df_GLES17$ClimateChange_W15, useNA = "always")
nrow(df_GLES17)- 14070    
prop.table(table(df_GLES17$ClimateChange_W15, useNA = "always"))
mean(df_GLES17$ClimateChange_W15, na.rm = T)
sd(df_GLES17$ClimateChange_W15, na.rm = T)

## n of respondents with valid answer in all six waves
desc_ClimateChange_subset <- c("ClimateChange_W4",
                              "ClimateChange_W8", 
                              "ClimateChange_W13", 
                              "ClimateChange_W14",
                              "ClimateChange_W15")

df_GLES17_descClimateChange <- df_GLES17[desc_ClimateChange_subset]
df_GLES17_descClimateChange <- df_GLES17_descClimateChange[complete.cases(df_GLES17_descClimateChange), ]
nrow(df_GLES17_descClimateChange)

######################################################################################/
#### <<>> APPENDIX 1 - Table A1.3 - Correlations Means and CFA Scores by Dimension ####
######################################################################################/

#### <<<>>> Comparison Anti-Elitism Mean Score to predicted CFA score ####
# We fit a cfa for each of the dimensions at each point in time and calculate correlation
# between mean score and predicted factor scores

#### Anti-Elitism - Wave 5

#fit CFA
mla_AE_W5  <- ' fs_AE_W5  =~ Anti_Elite_W5_1 + Anti_Elite_W5_2 + Anti_Elite_W5_3'
onefac3items_AE_W5 <- cfa(mla_AE_W5, data=df_GLES17) 
summary(onefac3items_AE_W5)

#merge cfa scores with original dataframe
idx_AE_W5 <- lavInspect(onefac3items_AE_W5, "case.idx")

vec_AE_W5_fs <- (lavPredict(onefac3items_AE_W5, newdata = df_GLES17[,c("Anti_Elite_W5_1", 
                                                                       "Anti_Elite_W5_2",
                                                                       "Anti_Elite_W5_3")]))
for (fs_AE_W5 in colnames(vec_AE_W5_fs)) {
  df_GLES17[idx_AE_W5, fs_AE_W5] <- vec_AE_W5_fs[ , fs_AE_W5]
}

#correlation
cor_AE_meanfs_W5 <- cor(df_GLES17$Anti_Elitism_Mean_W5, df_GLES17$fs_AE_W5, use="complete")

#### Anti-Elitism - Wave 8

#fit CFA
mla_AE_W8  <- ' fs_AE_W8  =~ Anti_Elite_W8_1 + Anti_Elite_W8_2 + Anti_Elite_W8_3'
onefac3items_AE_W8 <- cfa(mla_AE_W8, data=df_GLES17) 
summary(onefac3items_AE_W8)

#merge cfa scores with original dataframe
idx_AE_W8 <- lavInspect(onefac3items_AE_W8, "case.idx")
vec_AE_W8_fs <- (lavPredict(onefac3items_AE_W8, newdata = df_GLES17[,c("Anti_Elite_W8_1", 
                                                                       "Anti_Elite_W8_2",
                                                                       "Anti_Elite_W8_3")]))
for (fs_AE_W8 in colnames(vec_AE_W8_fs)) {
  df_GLES17[idx_AE_W8, fs_AE_W8] <- vec_AE_W8_fs[ , fs_AE_W8]
}
#correlation
cor_AE_meanfs_W8 <- cor(df_GLES17$Anti_Elitism_Mean_W8, df_GLES17$fs_AE_W8, use="complete")

#### Anti-Elitism - Wave 9

#fit CFA
mla_AE_W9  <- ' fs_AE_W9  =~ Anti_Elite_W9_1 + Anti_Elite_W9_2 + Anti_Elite_W9_3'
onefac3items_AE_W9 <- cfa(mla_AE_W9, data=df_GLES17) 
summary(onefac3items_AE_W9)

#merge cfa scores with original dataframe
idx_AE_W9 <- lavInspect(onefac3items_AE_W9, "case.idx")
vec_AE_W9_fs <- (lavPredict(onefac3items_AE_W9, newdata = df_GLES17[,c("Anti_Elite_W9_1", 
                                                                       "Anti_Elite_W9_2",
                                                                       "Anti_Elite_W9_3")]))
for (fs_AE_W9 in colnames(vec_AE_W9_fs)) {
  df_GLES17[idx_AE_W9, fs_AE_W9] <- vec_AE_W9_fs[ , fs_AE_W9]
}
#correlation
cor_AE_meanfs_W9 <- cor(df_GLES17$Anti_Elitism_Mean_W9, df_GLES17$fs_AE_W9, use="complete")

#### Anti-Elitism - Wave 13

#fit CFA
mla_AE_W13  <- ' fs_AE_W13  =~ Anti_Elite_W13_1 + Anti_Elite_W13_2 + Anti_Elite_W13_3'
onefac3items_AE_W13 <- cfa(mla_AE_W13, data=df_GLES17) 
summary(onefac3items_AE_W13)

#merge cfa scores with original dataframe
idx_AE_W13 <- lavInspect(onefac3items_AE_W13, "case.idx")
vec_AE_W13_fs <- (lavPredict(onefac3items_AE_W13, newdata = df_GLES17[,c("Anti_Elite_W13_1", 
                                                                         "Anti_Elite_W13_2",
                                                                         "Anti_Elite_W13_3")]))
for (fs_AE_W13 in colnames(vec_AE_W13_fs)) {
  df_GLES17[idx_AE_W13, fs_AE_W13] <- vec_AE_W13_fs[ , fs_AE_W13]
}
#correlation
cor_AE_meanfs_W13 <- cor(df_GLES17$Anti_Elitism_Mean_W13, df_GLES17$fs_AE_W13, use="complete")

#### Anti-Elitism - Wave 14

#fit CFA
mla_AE_W14  <- ' fs_AE_W14  =~ Anti_Elite_W14_1 + Anti_Elite_W14_2 + Anti_Elite_W14_3'
onefac3items_AE_W14 <- cfa(mla_AE_W14, data=df_GLES17) 
summary(onefac3items_AE_W14)

#merge cfa scores with original dataframe
idx_AE_W14 <- lavInspect(onefac3items_AE_W14, "case.idx")
vec_AE_W14_fs <- (lavPredict(onefac3items_AE_W14, newdata = df_GLES17[,c("Anti_Elite_W14_1", 
                                                                         "Anti_Elite_W14_2",
                                                                         "Anti_Elite_W14_3")]))
for (fs_AE_W14 in colnames(vec_AE_W14_fs)) {
  df_GLES17[idx_AE_W14, fs_AE_W14] <- vec_AE_W14_fs[ , fs_AE_W14]
}
#correlation
cor_AE_meanfs_W14 <- cor(df_GLES17$Anti_Elitism_Mean_W14, df_GLES17$fs_AE_W14, use="complete")
#### Anti-Elitism - Wave 15

#fit CFA
mla_AE_W15  <- ' fs_AE_W15  =~ Anti_Elite_W15_1 + Anti_Elite_W15_2 + Anti_Elite_W15_3'
onefac3items_AE_W15 <- cfa(mla_AE_W15, data=df_GLES17) 
summary(onefac3items_AE_W15)

#merge cfa scores with original dataframe
idx_AE_W15 <- lavInspect(onefac3items_AE_W15, "case.idx")
vec_AE_W15_fs <- (lavPredict(onefac3items_AE_W15, newdata = df_GLES17[,c("Anti_Elite_W15_1", 
                                                                         "Anti_Elite_W15_2",
                                                                         "Anti_Elite_W15_3")]))
for (fs_AE_W15 in colnames(vec_AE_W15_fs)) {
  df_GLES17[idx_AE_W15, fs_AE_W15] <- vec_AE_W15_fs[ , fs_AE_W15]
}
#correlation
cor_AE_meanfs_W15 <- cor(df_GLES17$Anti_Elitism_Mean_W15, df_GLES17$fs_AE_W15, use="complete")

#### Combine correlations and check range:
mean_cfa_cor_AE <- cbind(round(rbind(cor_AE_meanfs_W5, cor_AE_meanfs_W8,
                                     cor_AE_meanfs_W9, cor_AE_meanfs_W13,
                                     cor_AE_meanfs_W14, cor_AE_meanfs_W15),3),
                         c("Wave 5", "Wave 8", "Wave 9", "Wave 13",
                           "Wave 14", "Wave 15"))

#### <<<>>> Comparison Sovereignty Mean Score to predicted CFA score ####

# We fit a cfa for each of the dimensions at each point in time and calculate correlation
# between mean score and predicted factor scores

#### Sovereignty - Wave 5

#fit CFA
mla_SO_W5  <- ' fs_SO_W5  =~ Sovereignty_W5_1 + Sovereignty_W5_2 + Sovereignty_W5_3'
onefac3items_SO_W5 <- cfa(mla_SO_W5, data=df_GLES17) 
summary(onefac3items_SO_W5)

#merge cfa scores with original dataframe
idx_SO_W5 <- lavInspect(onefac3items_SO_W5, "case.idx")

vec_SO_W5_fs <- (lavPredict(onefac3items_SO_W5, newdata = df_GLES17[,c("Sovereignty_W5_1", 
                                                                       "Sovereignty_W5_2",
                                                                       "Sovereignty_W5_3")]))
for (fs_SO_W5 in colnames(vec_SO_W5_fs)) {
  df_GLES17[idx_SO_W5, fs_SO_W5] <- vec_SO_W5_fs[ , fs_SO_W5]
}

#correlation
cor_SO_meanfs_W5 <- cor(df_GLES17$Sovereignty_Mean_W5, df_GLES17$fs_SO_W5, use="complete")

#### Sovereignty - Wave 8

#fit CFA
mla_SO_W8  <- ' fs_SO_W8  =~ Sovereignty_W8_1 + Sovereignty_W8_2 + Sovereignty_W8_3'
onefac3items_SO_W8 <- cfa(mla_SO_W8, data=df_GLES17) 
summary(onefac3items_SO_W8)

#merge cfa scores with original dataframe
idx_SO_W8 <- lavInspect(onefac3items_SO_W8, "case.idx")
vec_SO_W8_fs <- (lavPredict(onefac3items_SO_W8, newdata = df_GLES17[,c("Sovereignty_W8_1", 
                                                                       "Sovereignty_W8_2",
                                                                       "Sovereignty_W8_3")]))
for (fs_SO_W8 in colnames(vec_SO_W8_fs)) {
  df_GLES17[idx_SO_W8, fs_SO_W8] <- vec_SO_W8_fs[ , fs_SO_W8]
}
#correlation
cor_SO_meanfs_W8 <- cor(df_GLES17$Sovereignty_Mean_W8, df_GLES17$fs_SO_W8, use="complete")

#### Sovereignty - Wave 9

#fit CFA
mla_SO_W9  <- ' fs_SO_W9  =~ Sovereignty_W9_1 + Sovereignty_W9_2 + Sovereignty_W9_3'
onefac3items_SO_W9 <- cfa(mla_SO_W9, data=df_GLES17) 
summary(onefac3items_SO_W9)

#merge cfa scores with original dataframe
idx_SO_W9 <- lavInspect(onefac3items_SO_W9, "case.idx")
vec_SO_W9_fs <- (lavPredict(onefac3items_SO_W9, newdata = df_GLES17[,c("Sovereignty_W9_1", 
                                                                       "Sovereignty_W9_2",
                                                                       "Sovereignty_W9_3")]))
for (fs_SO_W9 in colnames(vec_SO_W9_fs)) {
  df_GLES17[idx_SO_W9, fs_SO_W9] <- vec_SO_W9_fs[ , fs_SO_W9]
}
#correlation
cor_SO_meanfs_W9 <- cor(df_GLES17$Sovereignty_Mean_W9, df_GLES17$fs_SO_W9, use="complete")

#### Sovereignty - Wave 13

#fit CFA
mla_SO_W13  <- ' fs_SO_W13  =~ Sovereignty_W13_1 + Sovereignty_W13_2 + Sovereignty_W13_3'
onefac3items_SO_W13 <- cfa(mla_SO_W13, data=df_GLES17) 
summary(onefac3items_SO_W13)

#merge cfa scores with original dataframe
idx_SO_W13 <- lavInspect(onefac3items_SO_W13, "case.idx")
vec_SO_W13_fs <- (lavPredict(onefac3items_SO_W13, newdata = df_GLES17[,c("Sovereignty_W13_1", 
                                                                         "Sovereignty_W13_2",
                                                                         "Sovereignty_W13_3")]))
for (fs_SO_W13 in colnames(vec_SO_W13_fs)) {
  df_GLES17[idx_SO_W13, fs_SO_W13] <- vec_SO_W13_fs[ , fs_SO_W13]
}
#correlation
cor_SO_meanfs_W13 <- cor(df_GLES17$Sovereignty_Mean_W13, df_GLES17$fs_SO_W13, use="complete")

#### Sovereignty - Wave 14

#fit CFA
mla_SO_W14  <- ' fs_SO_W14  =~ Sovereignty_W14_1 + Sovereignty_W14_2 + Sovereignty_W14_3'
onefac3items_SO_W14 <- cfa(mla_SO_W14, data=df_GLES17) 
summary(onefac3items_SO_W14)

#merge cfa scores with original dataframe
idx_SO_W14 <- lavInspect(onefac3items_SO_W14, "case.idx")
vec_SO_W14_fs <- (lavPredict(onefac3items_SO_W14, newdata = df_GLES17[,c("Sovereignty_W14_1", 
                                                                         "Sovereignty_W14_2",
                                                                         "Sovereignty_W14_3")]))
for (fs_SO_W14 in colnames(vec_SO_W14_fs)) {
  df_GLES17[idx_SO_W14, fs_SO_W14] <- vec_SO_W14_fs[ , fs_SO_W14]
}
#correlation
cor_SO_meanfs_W14 <- cor(df_GLES17$Sovereignty_Mean_W14, df_GLES17$fs_SO_W14, use="complete")

#### Sovereignty - Wave 15

#fit CFA
mla_SO_W15  <- ' fs_SO_W15  =~ Sovereignty_W15_1 + Sovereignty_W15_2 + Sovereignty_W15_3'
onefac3items_SO_W15 <- cfa(mla_SO_W15, data=df_GLES17) 
summary(onefac3items_SO_W15)

#merge cfa scores with original dataframe
idx_SO_W15 <- lavInspect(onefac3items_SO_W15, "case.idx")
vec_SO_W15_fs <- (lavPredict(onefac3items_SO_W15, newdata = df_GLES17[,c("Sovereignty_W15_1", 
                                                                         "Sovereignty_W15_2",
                                                                         "Sovereignty_W15_3")]))
for (fs_SO_W15 in colnames(vec_SO_W15_fs)) {
  df_GLES17[idx_SO_W15, fs_SO_W15] <- vec_SO_W15_fs[ , fs_SO_W15]
}
#correlation
cor_SO_meanfs_W15 <- cor(df_GLES17$Sovereignty_Mean_W15, df_GLES17$fs_SO_W15, use="complete")

#### Combine correlations and check range:
mean_cfa_cor_SO <- cbind(round(rbind(cor_SO_meanfs_W5, cor_SO_meanfs_W8,
                                     cor_SO_meanfs_W9, cor_SO_meanfs_W13,
                                     cor_SO_meanfs_W14, cor_SO_meanfs_W15),3),
                         c("Wave 5", "Wave 8", "Wave 9", "Wave 13",
                           "Wave 14", "Wave 15"))


#### <<<>>> Comparison Homogeneity Mean Score to predicted CFA score ####
# We fit a cfa for each of the dimensions at each point in time and calculate correlation
# between mean score and predicted factor scores

#### Homogeneity - Wave 5

#fit CFA
mla_HO_W5  <- ' fs_HO_W5  =~ Homogeneity_W5_1 + Homogeneity_W5_2 + Homogeneity_W5_3'
onefac3items_HO_W5 <- cfa(mla_HO_W5, data=df_GLES17) 
summary(onefac3items_HO_W5)

#merge cfa scores with original dataframe
idx_HO_W5 <- lavInspect(onefac3items_HO_W5, "case.idx")

vec_HO_W5_fs <- (lavPredict(onefac3items_HO_W5, newdata = df_GLES17[,c("Homogeneity_W5_1", 
                                                                       "Homogeneity_W5_2",
                                                                       "Homogeneity_W5_3")]))
for (fs_HO_W5 in colnames(vec_HO_W5_fs)) {
  df_GLES17[idx_HO_W5, fs_HO_W5] <- vec_HO_W5_fs[ , fs_HO_W5]
}

#correlation
cor_HO_meanfs_W5 <- cor(df_GLES17$Homogeneity_Mean_W5, df_GLES17$fs_HO_W5, use="complete")

#### Homogeneity - Wave 8

#fit CFA
mla_HO_W8  <- ' fs_HO_W8  =~ Homogeneity_W8_1 + Homogeneity_W8_2 + Homogeneity_W8_3'
onefac3items_HO_W8 <- cfa(mla_HO_W8, data=df_GLES17) 
summary(onefac3items_HO_W8)

#merge cfa scores with original dataframe
idx_HO_W8 <- lavInspect(onefac3items_HO_W8, "case.idx")
vec_HO_W8_fs <- (lavPredict(onefac3items_HO_W8, newdata = df_GLES17[,c("Homogeneity_W8_1", 
                                                                       "Homogeneity_W8_2",
                                                                       "Homogeneity_W8_3")]))
for (fs_HO_W8 in colnames(vec_HO_W8_fs)) {
  df_GLES17[idx_HO_W8, fs_HO_W8] <- vec_HO_W8_fs[ , fs_HO_W8]
}
#correlation
cor_HO_meanfs_W8 <- cor(df_GLES17$Homogeneity_Mean_W8, df_GLES17$fs_HO_W8, use="complete")

#### Homogeneity - Wave 9

#fit CFA
mla_HO_W9  <- ' fs_HO_W9  =~ Homogeneity_W9_1 + Homogeneity_W9_2 + Homogeneity_W9_3'
onefac3items_HO_W9 <- cfa(mla_HO_W9, data=df_GLES17) 
summary(onefac3items_HO_W9)

#merge cfa scores with original dataframe
idx_HO_W9 <- lavInspect(onefac3items_HO_W9, "case.idx")
vec_HO_W9_fs <- (lavPredict(onefac3items_HO_W9, newdata = df_GLES17[,c("Homogeneity_W9_1", 
                                                                       "Homogeneity_W9_2",
                                                                       "Homogeneity_W9_3")]))
for (fs_HO_W9 in colnames(vec_HO_W9_fs)) {
  df_GLES17[idx_HO_W9, fs_HO_W9] <- vec_HO_W9_fs[ , fs_HO_W9]
}
#correlation
cor_HO_meanfs_W9 <- cor(df_GLES17$Homogeneity_Mean_W9, df_GLES17$fs_HO_W9, use="complete")

#### Homogeneity - Wave 13

#fit CFA
mla_HO_W13  <- ' fs_HO_W13  =~ Homogeneity_W13_1 + Homogeneity_W13_2 + Homogeneity_W13_3'
onefac3items_HO_W13 <- cfa(mla_HO_W13, data=df_GLES17) 
summary(onefac3items_HO_W13)

#merge cfa scores with original dataframe
idx_HO_W13 <- lavInspect(onefac3items_HO_W13, "case.idx")
vec_HO_W13_fs <- (lavPredict(onefac3items_HO_W13, newdata = df_GLES17[,c("Homogeneity_W13_1", 
                                                                         "Homogeneity_W13_2",
                                                                         "Homogeneity_W13_3")]))
for (fs_HO_W13 in colnames(vec_HO_W13_fs)) {
  df_GLES17[idx_HO_W13, fs_HO_W13] <- vec_HO_W13_fs[ , fs_HO_W13]
}
#correlation
cor_HO_meanfs_W13 <- cor(df_GLES17$Homogeneity_Mean_W13, df_GLES17$fs_HO_W13, use="complete")

#### Homogeneity - Wave 14

#fit CFA
mla_HO_W14  <- ' fs_HO_W14  =~ Homogeneity_W14_1 + Homogeneity_W14_2 + Homogeneity_W14_3'
onefac3items_HO_W14 <- cfa(mla_HO_W14, data=df_GLES17) 
summary(onefac3items_HO_W14)

#merge cfa scores with original dataframe
idx_HO_W14 <- lavInspect(onefac3items_HO_W14, "case.idx")
vec_HO_W14_fs <- (lavPredict(onefac3items_HO_W14, newdata = df_GLES17[,c("Homogeneity_W14_1", 
                                                                         "Homogeneity_W14_2",
                                                                         "Homogeneity_W14_3")]))
for (fs_HO_W14 in colnames(vec_HO_W14_fs)) {
  df_GLES17[idx_HO_W14, fs_HO_W14] <- vec_HO_W14_fs[ , fs_HO_W14]
}
#correlation
cor_HO_meanfs_W14 <- cor(df_GLES17$Homogeneity_Mean_W14, df_GLES17$fs_HO_W14, use="complete")

#### Homogeneity - Wave 15

#fit CFA
mla_HO_W15  <- ' fs_HO_W15  =~ Homogeneity_W15_1 + Homogeneity_W15_2 + Homogeneity_W15_3'
onefac3items_HO_W15 <- cfa(mla_HO_W15, data=df_GLES17) 
summary(onefac3items_HO_W15)

#merge cfa scores with original dataframe
idx_HO_W15 <- lavInspect(onefac3items_HO_W15, "case.idx")
vec_HO_W15_fs <- (lavPredict(onefac3items_HO_W15, newdata = df_GLES17[,c("Homogeneity_W15_1", 
                                                                         "Homogeneity_W15_2",
                                                                         "Homogeneity_W15_3")]))
for (fs_HO_W15 in colnames(vec_HO_W15_fs)) {
  df_GLES17[idx_HO_W15, fs_HO_W15] <- vec_HO_W15_fs[ , fs_HO_W15]
}
#correlation
cor_HO_meanfs_W15 <- cor(df_GLES17$Homogeneity_Mean_W15, df_GLES17$fs_HO_W15, use="complete")

#### Combine correlations and check range:
mean_cfa_cor_HO <- cbind(round(rbind(cor_HO_meanfs_W5, cor_HO_meanfs_W8,
                                     cor_HO_meanfs_W9, cor_HO_meanfs_W13,
                                     cor_HO_meanfs_W14, cor_HO_meanfs_W15),3),
                         c("Wave 5", "Wave 8", "Wave 9", "Wave 13",
                           "Wave 14", "Wave 15"))

#### <<>> Table
mean_cfa_cor_AE #Anti-Elitism
mean_cfa_cor_SO #Sovereignty
mean_cfa_cor_HO #Homogeneity

################################################################################/
#### <<>> APPENDIX 2 - Table A2.1 - Measurement Invariance by Dimension      ####
################################################################################/

## Anti-Elitism
tab_invariance_ae

## Sovereignty
tab_invariance_sov

## Homogeneity
tab_invariance_ho

################################################################################/
#### <<>> APPENDIX 3 - Table A3.1 - Standard Deviations within absolute stability groups   ####
################################################################################/

#create dataframe
WPSTd_sub <- c("lfdn", "StablePop_V2_W5W15", "Populism_Goertz_AbsoluteMinimum_W5",
               "Populism_Goertz_AbsoluteMinimum_W8", "Populism_Goertz_AbsoluteMinimum_W9",
               "Populism_Goertz_AbsoluteMinimum_W13", "Populism_Goertz_AbsoluteMinimum_W14",
               "Populism_Goertz_AbsoluteMinimum_W15")

df_GLES17_WPSTd_sub <- df_GLES17[WPSTd_sub]
df_GLES17_WPSTd_sub <- df_GLES17_WPSTd_sub[complete.cases(df_GLES17_WPSTd_sub), ]

# Calculate Within Person Standard Deviation (with n-1)
df_GLES17_WPSTd_sub$sd <- sqrt(rowSums((df_GLES17_WPSTd_sub[,3:8] - rowMeans(df_GLES17_WPSTd_sub[,3:8]))^2)/5)

# Calculate Average by stability Group
AVStd_Unstable = mean(df_GLES17_WPSTd_sub$sd[df_GLES17_WPSTd_sub$StablePop_V2_W5W15 ==1 ])
AVStd_Stable = mean(df_GLES17_WPSTd_sub$sd[df_GLES17_WPSTd_sub$StablePop_V2_W5W15 >1])
# are the sds different from one another?
t.test(df_GLES17_WPSTd_sub$sd[df_GLES17_WPSTd_sub$StablePop_V2_W5W15 ==1 ],
       df_GLES17_WPSTd_sub$sd[df_GLES17_WPSTd_sub$StablePop_V2_W5W15 == 2 | 
                                df_GLES17_WPSTd_sub$StablePop_V2_W5W15 == 3])

## Table A3.1
AVStd_Unstable
AVStd_Stable

######################################################################################/
#### <<>> APPENDIX 4 - Figure A4.1  - Stable Non-Populists and Populists & Comparison (Global Analysis; mid category as ambivalence/lack of opinion) ####
######################################################################################/

## Plot compares stable populist attitude holders (INCLUDING those who are consistently
## in the "neither/nor" category in all six panel waves), and "other" 
## category plus comparison to other constructs (political interest, satisfaction
## with government, perceived economic situation and position on environment vs
## economy). Baseline is W5 for all variables but environment variable where
## baseline is W4 (global stability with incrementally increasing time spans)

#### <<<>>> For middle category == ambivalence/lack of opinion + individual pop dimensions

#Summarize Data - W5W8
# Populism
tab_a_pop <- df_GLES17 %>%
  select(starts_with("StablePop_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_W5W8) %>%
  mutate(freq = n / sum(n),
         time=1,
         var=1) %>%
  rename(Category=StablePop_W5W8)
# Political Interest
tab_a_polint <- df_GLES17 %>%
  select(starts_with("StableInt_W")) %>%
  filter(!is.na(StableInt_W5W15)) %>%
  count(StableInt_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=2) %>%
  rename(Category=StableInt_W5W8)
# Satisfaction with Government
tab_a_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(!is.na(StableGovSat_W5W15)) %>%
  count(StableGovSat_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=3) %>%
  rename(Category=StableGovSat_W5W8)
# Sociotropic Economic Perceptions
tab_a_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(!is.na(StableEcon_W5W15)) %>%
  count(StableEcon_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=4) %>%
  rename(Category=StableEcon_W5W8)
# Environment vs Economy 
tab_a_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(!is.na(StableClimate_W4W15)) %>%
  count(StableClimate_W4W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=5) %>%
  rename(Category=StableClimate_W4W8)
# Anti_Elitism
tab_a_Anti_Elite <- df_GLES17 %>%
  select(starts_with("StableAntiElite_")) %>%
  filter(!is.na(StableAntiElite_W5W15)) %>%
  count(StableAntiElite_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=6) %>%
  rename(Category=StableAntiElite_W5W8)
# People Sovereignty
tab_a_PeopleSov <- df_GLES17 %>%
  select(starts_with("Stable_PeopleSov_")) %>%
  filter(!is.na(Stable_PeopleSov_W5W15)) %>%
  count(Stable_PeopleSov_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=7) %>%
  rename(Category=Stable_PeopleSov_W5W8)
# Homogeneity
tab_a_Homogeneity <- df_GLES17 %>%
  select(starts_with("Stable_Homogeneity_")) %>%
  filter(!is.na(Stable_Homogeneity_W5W15)) %>%
  count(Stable_Homogeneity_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=8) %>%
  rename(Category=Stable_Homogeneity_W5W8)

####Summarize Data - W5W9
#Populism
tab_b_pop <- df_GLES17 %>%
  select(starts_with("StablePop_W")) %>%
  filter(!is.na(StablePop_W5W15)) %>%
  count(StablePop_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=1) %>%
  rename(Category=StablePop_W5W9)
# Political Interest
tab_b_polint <- df_GLES17 %>%
  select(starts_with("StableInt_W")) %>%
  filter(!is.na(StableInt_W5W15)) %>%
  count(StableInt_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=2) %>%
  rename(Category=StableInt_W5W9)

# Satisfaction with Government (not available)
freq <- c(NA, NA, NA)
time <- c(2,2,2)
var <- c(3, 3, 3)
n <- c(NA, NA, NA)
Category <- c(1,2,3)

tab_b_SatGov <- as.data.frame(cbind(Category, n, freq, time, var))

# Sociotropic Economic Perceptions (not available)
var <- c(4, 4, 4)
Category <- c(1,2,3)

tab_b_EcoPercSocio <- as.data.frame(cbind(Category, n, freq, time, var))

# Environment vs Economy  (not available)
var <- c(5, 5, 5)
tab_b_ClimateChange <- as.data.frame(cbind(Category, n, freq, time, var))

# Anti_Elitism
tab_b_Anti_Elite <- df_GLES17 %>%
  select(starts_with("StableAntiElite_")) %>%
  filter(!is.na(StableAntiElite_W5W15)) %>%
  count(StableAntiElite_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=6) %>%
  rename(Category=StableAntiElite_W5W9)
# People Sovereignty
tab_b_PeopleSov <- df_GLES17 %>%
  select(starts_with("Stable_PeopleSov_")) %>%
  filter(!is.na(Stable_PeopleSov_W5W15)) %>%
  count(Stable_PeopleSov_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=7) %>%
  rename(Category=Stable_PeopleSov_W5W9)
# Homogeneity
tab_b_Homogeneity <- df_GLES17 %>%
  select(starts_with("Stable_Homogeneity_")) %>%
  filter(!is.na(Stable_Homogeneity_W5W15)) %>%
  count(Stable_Homogeneity_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=8) %>%
  rename(Category=Stable_Homogeneity_W5W9)

#Summarize Data - W5W13
#Populism
tab_c_pop <- df_GLES17 %>%
  select(starts_with("StablePop_W")) %>%
  filter(!is.na(StablePop_W5W15)) %>%
  count(StablePop_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=1) %>%
  rename(Category=StablePop_W5W13)
# Political Interest
tab_c_polint <- df_GLES17 %>%
  select(starts_with("StableInt_W")) %>%
  filter(!is.na(StableInt_W5W15)) %>%
  count(StableInt_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=2) %>%
  rename(Category=StableInt_W5W13)
# Satisfaction with Government
tab_c_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(!is.na(StableGovSat_W5W15)) %>%
  count(StableGovSat_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=3) %>%
  rename(Category=StableGovSat_W5W13)
# Sociotropic Economic Perceptions
tab_c_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(!is.na(StableEcon_W5W15)) %>%
  count(StableEcon_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=4) %>%
  rename(Category=StableEcon_W5W13)
# Environment vs Economy 
tab_c_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(!is.na(StableClimate_W4W15)) %>%
  count(StableClimate_W4W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=5) %>%
  rename(Category=StableClimate_W4W13)
# Anti_Elitism
tab_c_Anti_Elite <- df_GLES17 %>%
  select(starts_with("StableAntiElite_")) %>%
  filter(!is.na(StableAntiElite_W5W15)) %>%
  count(StableAntiElite_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=6) %>%
  rename(Category=StableAntiElite_W5W13)
# People Sovereignty
tab_c_PeopleSov <- df_GLES17 %>%
  select(starts_with("Stable_PeopleSov_")) %>%
  filter(!is.na(Stable_PeopleSov_W5W15)) %>%
  count(Stable_PeopleSov_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=7) %>%
  rename(Category=Stable_PeopleSov_W5W13)
# Homogeneity
tab_c_Homogeneity <- df_GLES17 %>%
  select(starts_with("Stable_Homogeneity_")) %>%
  filter(!is.na(Stable_Homogeneity_W5W15)) %>%
  count(Stable_Homogeneity_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=8) %>%
  rename(Category=Stable_Homogeneity_W5W13)

#Summarize Data - W5W14
#Populism
tab_d_pop <- df_GLES17 %>%
  select(starts_with("StablePop_W")) %>%
  filter(!is.na(StablePop_W5W15)) %>%
  count(StablePop_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=1) %>%
  rename(Category=StablePop_W5W14)
# Political Interest
tab_d_polint <- df_GLES17 %>%
  select(starts_with("StableInt_W")) %>%
  filter(!is.na(StableInt_W5W15)) %>%
  count(StableInt_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=2) %>%
  rename(Category=StableInt_W5W14)
# Satisfaction with Government
tab_d_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(!is.na(StableGovSat_W5W15)) %>%
  count(StableGovSat_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=3) %>%
  rename(Category=StableGovSat_W5W14)
# Sociotropic Economic Perceptions
tab_d_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(!is.na(StableEcon_W5W15)) %>%
  count(StableEcon_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=4) %>%
  rename(Category=StableEcon_W5W14)
# Environment vs Economy 
tab_d_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(!is.na(StableClimate_W4W15)) %>%
  count(StableClimate_W4W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=5) %>%
  rename(Category=StableClimate_W4W14)
# Anti_Elitism
tab_d_Anti_Elite <- df_GLES17 %>%
  select(starts_with("StableAntiElite_")) %>%
  filter(!is.na(StableAntiElite_W5W15)) %>%
  count(StableAntiElite_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=6) %>%
  rename(Category=StableAntiElite_W5W14)
# People Sovereignty
tab_d_PeopleSov <- df_GLES17 %>%
  select(starts_with("Stable_PeopleSov_")) %>%
  filter(!is.na(Stable_PeopleSov_W5W15)) %>%
  count(Stable_PeopleSov_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=7) %>%
  rename(Category=Stable_PeopleSov_W5W14)
# Homogeneity
tab_d_Homogeneity <- df_GLES17 %>%
  select(starts_with("Stable_Homogeneity_")) %>%
  filter(!is.na(Stable_Homogeneity_W5W15)) %>%
  count(Stable_Homogeneity_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=8) %>%
  rename(Category=Stable_Homogeneity_W5W14)


#Summarize Data - W5W15
#Populism
tab_e_pop <- df_GLES17 %>%
  select(starts_with("StablePop_W")) %>%
  filter(!is.na(StablePop_W5W15)) %>%
  count(StablePop_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=1) %>%
  rename(Category=StablePop_W5W15)
# Political Interest
tab_e_polint <- df_GLES17 %>%
  select(starts_with("StableInt_W")) %>%
  filter(!is.na(StableInt_W5W15)) %>%
  count(StableInt_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=2) %>%
  rename(Category=StableInt_W5W15)
# Satisfaction with Government
tab_e_SatGov <- df_GLES17 %>%
  select(starts_with("StableGovSat_")) %>%
  filter(!is.na(StableGovSat_W5W15)) %>%
  count(StableGovSat_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=3) %>%
  rename(Category=StableGovSat_W5W15)
# Sociotropic Economic Perceptions
tab_e_EcoPercSocio <- df_GLES17 %>%
  select(starts_with("StableEcon_")) %>%
  filter(!is.na(StableEcon_W5W15)) %>%
  count(StableEcon_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=4) %>%
  rename(Category=StableEcon_W5W15)
# Environment vs Economy 
tab_e_ClimateChange <- df_GLES17 %>%
  select(starts_with("StableClimate_")) %>%
  filter(!is.na(StableClimate_W4W15)) %>%
  count(StableClimate_W4W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=5) %>%
  rename(Category=StableClimate_W4W15)
# Anti_Elitism
tab_e_Anti_Elite <- df_GLES17 %>%
  select(starts_with("StableAntiElite_")) %>%
  filter(!is.na(StableAntiElite_W5W15)) %>%
  count(StableAntiElite_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=6) %>%
  rename(Category=StableAntiElite_W5W15)
# People Sovereignty
tab_e_PeopleSov <- df_GLES17 %>%
  select(starts_with("Stable_PeopleSov_")) %>%
  filter(!is.na(Stable_PeopleSov_W5W15)) %>%
  count(Stable_PeopleSov_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=7) %>%
  rename(Category=Stable_PeopleSov_W5W15)
# Homogeneity
tab_e_Homogeneity <- df_GLES17 %>%
  select(starts_with("Stable_Homogeneity_")) %>%
  filter(!is.na(Stable_Homogeneity_W5W15)) %>%
  count(Stable_Homogeneity_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=8) %>%
  rename(Category=Stable_Homogeneity_W5W15)

#Build dataset for plot:
df_stable_plot <- as.data.frame(rbind(tab_a_pop, tab_b_pop, tab_c_pop, 
                                      tab_d_pop, tab_e_pop,
                                      tab_a_polint, tab_b_polint, tab_c_polint,
                                      tab_d_polint, tab_e_polint,
                                      tab_a_SatGov, tab_b_SatGov, tab_c_SatGov,
                                      tab_d_SatGov, tab_e_SatGov,
                                      tab_a_EcoPercSocio, tab_b_EcoPercSocio, tab_c_EcoPercSocio,
                                      tab_d_EcoPercSocio, tab_e_EcoPercSocio,
                                      tab_a_ClimateChange, tab_b_ClimateChange, tab_c_ClimateChange,
                                      tab_d_ClimateChange, tab_e_ClimateChange,
                                      tab_a_Anti_Elite, tab_b_Anti_Elite, tab_c_Anti_Elite,
                                      tab_d_Anti_Elite, tab_e_Anti_Elite,
                                      tab_a_PeopleSov, tab_b_PeopleSov, tab_c_PeopleSov,
                                      tab_d_PeopleSov, tab_e_PeopleSov,
                                      tab_a_Homogeneity, tab_b_Homogeneity, tab_c_Homogeneity,
                                      tab_d_Homogeneity, tab_e_Homogeneity))
df_stable_plot$freq <- round(df_stable_plot$freq,2)

# Add time lapsed variable
df_stable_plot$time_lapsed <- NA
df_stable_plot$time_lapsed[df_stable_plot$time==1] <- 0.08333333
df_stable_plot$time_lapsed[df_stable_plot$time==2] <- 0.5
df_stable_plot$time_lapsed[df_stable_plot$time==3] <- 2.666667
df_stable_plot$time_lapsed[df_stable_plot$time==4] <- 3.166667
df_stable_plot$time_lapsed[df_stable_plot$time==5] <- 3.583333

#Add value labels:
df_stable_plot$Category <- factor(df_stable_plot$Category,
                                  labels=c("Unstable", "Stable \n Positive",
                                           "Stable \n Negative", "Stable middle"))
df_stable_plot$time <- factor(df_stable_plot$time,
                              labels=c("1", "2",
                                       "3", "4",
                                       "5"))
df_stable_plot$var <- factor(df_stable_plot$var,
                             labels=c("Populism", "Political \n Interest", 
                                      "Satisfaction \n with Government",
                                      "Economic \n Perceptions",
                                      "Climate \n Protection",
                                      "Anti-Elitism", "People Sovereignty",
                                      "Homogeneity"))


#### <<<>>> Step 2: plot (populism + comparison concepts for main text)

# plot - populism plus comparison concepts
plot_desc_overtime_pop_V2 <- df_stable_plot %>%
  filter(!is.na(freq) & Category=="Unstable" & var!="Anti-Elitism" & 
           var!="People Sovereignty" & var!="Homogeneity" ) %>%
  ggplot(., aes(x=time_lapsed, y=freq, colour=var, shape=var, group=var)) +
  geom_point(size=2) +
  geom_line() + 
  scale_color_manual(values=c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442")) +
  base_breaks_x3(df_stable_plot$time_lapsed) +
  base_breaks_y3(df_stable_plot$freq) +
  scale_y_continuous(labels=scales::percent) +
  theme_minimal() +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  xlab("") +
  ylab("Percent") +
  xlab("Time since first measurement (years)") +
  guides(color=guide_legend(nrow=1, byrow=TRUE))  

#### Safe Plot

tiff("APPENDIX_4_FIGURE_4.1_Pop_Over_Time_Desc_V2.tiff",
     units="in", width=8, height=6, res=900, compression = "lzw")
plot_desc_overtime_pop_V2
dev.off()

################################################################################/
#### <<>> APPENDIX 4- Table A4.1 - Populist Attitudes Opinion Switches       ####
################################################################################/


#neither agree nor disagree=ambivalence/lack of opinion
round(prop.table(table(df_GLES17$switch.count2))*100,2)

################################################################################################################/
#### <<>> APPENDIX 4 - Figure A4.2 Correlation with Democratic Attitudes by Stability (Middle Category as ambivalence/lack of opinion) ####
################################################################################################################/

## Estimate correlation with three democratic attitudes measured in Wave 15:
# 1. every party should have the chance to become part of the government (variable name: DemAtt_IT1_WX)
# 2. everyone should have the right to stand up for their opinion even if the majority has a different opinion (variable name: DemAtt_IT2_WX)
# 3. a vibrant democracy is unthinkable without an opposition (variable name: DemAtt_IT3_WX)
#
# Correlation altogether (with populist attitudes measured in waves 14 and 15) and then
# repeat step 1 but distinguish stable and non-stable populist.
# 
# Create variable that combines stable non populists and stable populists into
# a single category resulting in:
# 1=unstable
# 2=stable (including respondents who are stable in the middle category)
df_GLES17$StablePop_V2 <- df_GLES17$StablePop_W5W15
df_GLES17$StablePop_V2[df_GLES17$StablePop_W5W15>1] <- 2 #Stable Non-Populists

## Correlation with no distinctions already exist; no need to replicate

## Correlation - stable populists (Wave 14 populist measures):
pop_dem_cor_IT1_W14_stab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop_V2==2], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop_V2==2], use = "complete")
pop_dem_cor_IT2_W14_stab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop_V2==2], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop_V2==2], use = "complete")
pop_dem_cor_IT3_W14_stab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop_V2==2], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop_V2==2], use = "complete")

## Correlation - unstable populists (Wave 14 populist measures):
pop_dem_cor_IT1_W14_unstab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop_V2==1], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop_V2==1], use = "complete")
pop_dem_cor_IT2_W14_unstab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop_V2==1], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop_V2==1], use = "complete")
pop_dem_cor_IT3_W14_unstab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W14[df_GLES17$StablePop_V2==1], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop_V2==1], use = "complete")


## Correlation - stable populists (Wave 15 populist measures):
pop_dem_cor_IT1_W15_stab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop_V2==2], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop_V2==2], use = "complete")
pop_dem_cor_IT2_W15_stab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop_V2==2], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop_V2==2], use = "complete")
pop_dem_cor_IT3_W15_stab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop_V2==2], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop_V2==2], use = "complete")


## Correlation - unstable populists (Wave 15 populist measures):
pop_dem_cor_IT1_W15_unstab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop_V2==1], df_GLES17$DemAtt_IT1_W15[df_GLES17$StablePop_V2==1], use = "complete")
pop_dem_cor_IT2_W15_unstab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop_V2==1], df_GLES17$DemAtt_IT2_W15[df_GLES17$StablePop_V2==1], use = "complete")
pop_dem_cor_IT3_W15_unstab_V2 <- cor.test(df_GLES17$Populism_Goertz_AbsoluteMinimum_W15[df_GLES17$StablePop_V2==1], df_GLES17$DemAtt_IT3_W15[df_GLES17$StablePop_V2==1], use = "complete")

# Build dataframe for plotting:
# Variables: Wave, Combined/Stable/Unstable, Cor_Variable, Correlation, CI_Low, CI_Upper
df_cor_plot_V2 <- as.data.frame(rbind(c(1, 1, 1, pop_dem_cor_IT1_W14$estimate, pop_dem_cor_IT1_W14$conf.int[1], pop_dem_cor_IT1_W14$conf.int[2]),
                                   c(1, 1, 2, pop_dem_cor_IT2_W14$estimate, pop_dem_cor_IT2_W14$conf.int[1], pop_dem_cor_IT2_W14$conf.int[2]),
                                   c(1, 1, 3, pop_dem_cor_IT3_W14$estimate, pop_dem_cor_IT3_W14$conf.int[1], pop_dem_cor_IT3_W14$conf.int[2]),
                                   c(2, 1, 1, pop_dem_cor_IT1_W15$estimate, pop_dem_cor_IT1_W15$conf.int[1], pop_dem_cor_IT1_W15$conf.int[2]),
                                   c(2, 1, 2, pop_dem_cor_IT2_W15$estimate, pop_dem_cor_IT2_W15$conf.int[1], pop_dem_cor_IT2_W15$conf.int[2]),
                                   c(2, 1, 3, pop_dem_cor_IT3_W15$estimate, pop_dem_cor_IT3_W15$conf.int[1], pop_dem_cor_IT3_W15$conf.int[2]),
                                   c(1, 2, 1, pop_dem_cor_IT1_W14_stab_V2$estimate, pop_dem_cor_IT1_W14_stab_V2$conf.int[1], pop_dem_cor_IT1_W14_stab_V2$conf.int[2]),
                                   c(1, 2, 2, pop_dem_cor_IT2_W14_stab_V2$estimate, pop_dem_cor_IT2_W14_stab_V2$conf.int[1], pop_dem_cor_IT2_W14_stab_V2$conf.int[2]),
                                   c(1, 2, 3, pop_dem_cor_IT3_W14_stab_V2$estimate, pop_dem_cor_IT3_W14_stab_V2$conf.int[1], pop_dem_cor_IT3_W14_stab_V2$conf.int[2]),
                                   c(2, 2, 1, pop_dem_cor_IT1_W15_stab_V2$estimate, pop_dem_cor_IT1_W15_stab_V2$conf.int[1], pop_dem_cor_IT1_W15_stab_V2$conf.int[2]),
                                   c(2, 2, 2, pop_dem_cor_IT2_W15_stab_V2$estimate, pop_dem_cor_IT2_W15_stab_V2$conf.int[1], pop_dem_cor_IT2_W15_stab_V2$conf.int[2]),
                                   c(2, 2, 3, pop_dem_cor_IT3_W15_stab_V2$estimate, pop_dem_cor_IT3_W15_stab_V2$conf.int[1], pop_dem_cor_IT3_W15_stab_V2$conf.int[2]),
                                   c(1, 3, 1, pop_dem_cor_IT1_W14_unstab_V2$estimate, pop_dem_cor_IT1_W14_unstab_V2$conf.int[1], pop_dem_cor_IT1_W14_unstab_V2$conf.int[2]),
                                   c(1, 3, 2, pop_dem_cor_IT2_W14_unstab_V2$estimate, pop_dem_cor_IT2_W14_unstab_V2$conf.int[1], pop_dem_cor_IT2_W14_unstab_V2$conf.int[2]),
                                   c(1, 3, 3, pop_dem_cor_IT3_W14_unstab_V2$estimate, pop_dem_cor_IT3_W14_unstab_V2$conf.int[1], pop_dem_cor_IT3_W14_unstab_V2$conf.int[2]),
                                   c(2, 3, 1, pop_dem_cor_IT1_W15_unstab_V2$estimate, pop_dem_cor_IT1_W15_unstab_V2$conf.int[1], pop_dem_cor_IT1_W15_unstab_V2$conf.int[2]),
                                   c(2, 3, 2, pop_dem_cor_IT2_W15_unstab_V2$estimate, pop_dem_cor_IT2_W15_unstab_V2$conf.int[1], pop_dem_cor_IT2_W15_unstab_V2$conf.int[2]),
                                   c(2, 3, 3, pop_dem_cor_IT3_W15_unstab_V2$estimate, pop_dem_cor_IT3_W15_unstab_V2$conf.int[1], pop_dem_cor_IT3_W15_unstab_V2$conf.int[2])
))
names(df_cor_plot_V2)[1] <- "Wave" #Panel Wave from which populist attitudes are taken
names(df_cor_plot_V2)[2] <- "Distinction"
names(df_cor_plot_V2)[3] <- "Cor_Variable"
names(df_cor_plot_V2)[4] <- "Correlation"
names(df_cor_plot_V2)[5] <- "CI_Low"
names(df_cor_plot_V2)[6] <- "CI_Upper"
# Add labels for variables:
df_cor_plot_V2$Wave <- as.factor(df_cor_plot_V2$Wave)
levels(df_cor_plot_V2$Wave) <- c("W5", "W6") 
#df_cor_plot$Distinction <- as.factor(df_cor_plot$Distinction)
#levels(df_cor_plot$Distinction) <- c("Combined", "Stable", "Unstable")
df_cor_plot_V2$Cor_Variable <- as.factor(df_cor_plot_V2$Cor_Variable)
levels(df_cor_plot_V2$Cor_Variable) <- c("Every party should have \n the chance to become part \n of the government.",
                                      "Everyone should have the \n right to stand up for their \n opinion even if the  \n majority has a different opinion", 
                                      "A vibrant democracy is \n unthinkable without an opposition.")

## Plot
df_test_cor_plot_V2 <- df_cor_plot_V2 %>%
  filter(Wave=="W6") %>%
  ggplot(.,
         aes(x=Distinction, y=Correlation, color = as.factor(Distinction))) + 
  geom_pointrange(aes(ymin=CI_Low, ymax=CI_Upper), size=0.7) +
  geom_hline(yintercept=0, color='red', size=0.5)+
  facet_wrap( ~ Cor_Variable)+
  coord_flip()+
  xlab("")+
  theme_minimal() +
  base_breaks_x1(df_cor_plot_V2$Distinction) +
  base_breaks_y1(df_cor_plot_V2$Correlation) +
  theme(legend.position="bottom") +
  ylim(-0.15, 0.15) +
  scale_color_manual(values=c("#000000", "#E69F00", "#56B4E9")) +
  theme(legend.position = "none")+ 
  scale_x_continuous(breaks=c(1,2,3),
                     labels = c("Combined", 
                                "Stable only", 
                                "Unstable only"))

#### Safe Plot

tiff("APPENDIX_4_Figure_4.2_Alternative_Corellation_Democratic_Attitudes.tiff",
     units="in", width=8, height=4.5, res=900, compression = "lzw")
df_test_cor_plot_V2
dev.off()


######################################################################################/
#### <<>> APPENDIX 5 - Figure A5.1 - Correlations for Populist Dimensions (Appendix)  ####
#######################################################################################/

#### <<<>>> Step 1 - Anti-Elitism Correlations

# Generate subset of respondents for whom there is valid data in each of the six panel waves:
subset_correlation_AE <- c("lfdn", "Anti_Elitism_Mean_W5",
                           "Anti_Elitism_Mean_W8", "Anti_Elitism_Mean_W9",
                           "Anti_Elitism_Mean_W13", "Anti_Elitism_Mean_W14",
                           "Anti_Elitism_Mean_W15")
subset_correlation_AE <- df_GLES17[subset_correlation_AE]
subset_correlation_AE <- subset_correlation_AE[complete.cases(subset_correlation_AE), ]
# correlations:
corrW5W8_AE <- cor.test(x=subset_correlation_AE$Anti_Elitism_Mean_W5, 
                        y=subset_correlation_AE$Anti_Elitism_Mean_W8, method = 'pearson', exact = FALSE)
corrW5W9_AE <- cor.test(x=subset_correlation_AE$Anti_Elitism_Mean_W5, 
                        y=subset_correlation_AE$Anti_Elitism_Mean_W9, method = 'pearson', exact = FALSE)
corrW5W13_AE <- cor.test(x=subset_correlation_AE$Anti_Elitism_Mean_W5, 
                         y=subset_correlation_AE$Anti_Elitism_Mean_W13, method = 'pearson', exact = FALSE)
corrW5W14_AE <- cor.test(x=subset_correlation_AE$Anti_Elitism_Mean_W5,
                         y=subset_correlation_AE$Anti_Elitism_Mean_W14, method = 'pearson', exact = FALSE)
corrW5W15_AE <- cor.test(x=subset_correlation_AE$Anti_Elitism_Mean_W5, 
                         y=subset_correlation_AE$Anti_Elitism_Mean_W15, method = 'pearson', exact = FALSE)
# Estimates & CIs
correlation_estimates_AE <- c(corrW5W8_AE$estimate, corrW5W9_AE$estimate, corrW5W13_AE$estimate, corrW5W14_AE$estimate, corrW5W15_AE$estimate)
correlation_estimates_AE <- format(round(correlation_estimates_AE, 3), nsmall = 3)
correlation_estimates_AE <- as.data.frame(correlation_estimates_AE)
names(correlation_estimates_AE)[1] <- "correlation"

correlation_CI_Low_AE <- c(corrW5W8_AE$conf.int[1], corrW5W9_AE$conf.int[1], corrW5W13_AE$conf.int[1], corrW5W14_AE$conf.int[1], corrW5W15_AE$conf.int[1])
correlation_CI_Low_AE <- format(round(correlation_CI_Low_AE, 3), nsmall = 3)
correlation_CI_Low_AE <- as.data.frame(correlation_CI_Low_AE)
names(correlation_CI_Low_AE)[1] <- "Lower"

correlation_CI_Upper_AE <- c(corrW5W8_AE$conf.int[2], corrW5W9_AE$conf.int[2], corrW5W13_AE$conf.int[2], corrW5W14_AE$conf.int[2], corrW5W15_AE$conf.int[2])
correlation_CI_Upper_AE <- format(round(correlation_CI_Upper_AE, 3), nsmall = 3)
correlation_CI_Upper_AE <- as.data.frame(correlation_CI_Upper_AE)
names(correlation_CI_Upper_AE)[1] <- "Upper"


#### <<<>>> Step 2 - Homogeneity Correlations

# Generate subset of respondents for whom there is valid data in each of the six panel waves:
subset_correlation_HOM <- c("lfdn", "Homogeneity_Mean_W5",
                            "Homogeneity_Mean_W8", "Homogeneity_Mean_W9",
                            "Homogeneity_Mean_W13", "Homogeneity_Mean_W14",
                            "Homogeneity_Mean_W15")
subset_correlation_HOM <- df_GLES17[subset_correlation_HOM]
subset_correlation_HOM <- subset_correlation_HOM[complete.cases(subset_correlation_HOM), ]
# correlations:
corrW5W8_HOM <- cor.test(x=subset_correlation_HOM$Homogeneity_Mean_W5, 
                         y=subset_correlation_HOM$Homogeneity_Mean_W8, method = 'pearson', exact = FALSE)
corrW5W9_HOM <- cor.test(x=subset_correlation_HOM$Homogeneity_Mean_W5, 
                         y=subset_correlation_HOM$Homogeneity_Mean_W9, method = 'pearson', exact = FALSE)
corrW5W13_HOM <- cor.test(x=subset_correlation_HOM$Homogeneity_Mean_W5, 
                          y=subset_correlation_HOM$Homogeneity_Mean_W13, method = 'pearson', exact = FALSE)
corrW5W14_HOM <- cor.test(x=subset_correlation_HOM$Homogeneity_Mean_W5,
                          y=subset_correlation_HOM$Homogeneity_Mean_W14, method = 'pearson', exact = FALSE)
corrW5W15_HOM <- cor.test(x=subset_correlation_HOM$Homogeneity_Mean_W5, 
                          y=subset_correlation_HOM$Homogeneity_Mean_W15, method = 'pearson', exact = FALSE)

# Estimates & CIs
correlation_estimates_HOM <- c(corrW5W8_HOM$estimate, corrW5W9_HOM$estimate, corrW5W13_HOM$estimate, corrW5W14_HOM$estimate, corrW5W15_HOM$estimate)
correlation_estimates_HOM <- format(round(correlation_estimates_HOM, 3), nsmall = 3)
correlation_estimates_HOM <- as.data.frame(correlation_estimates_HOM)
names(correlation_estimates_HOM)[1] <- "correlation"

correlation_CI_Low_HOM <- c(corrW5W8_HOM$conf.int[1], corrW5W9_HOM$conf.int[1], corrW5W13_HOM$conf.int[1], corrW5W14_HOM$conf.int[1], corrW5W15_HOM$conf.int[1])
correlation_CI_Low_HOM <- format(round(correlation_CI_Low_HOM, 3), nsmall = 3)
correlation_CI_Low_HOM <- as.data.frame(correlation_CI_Low_HOM)
names(correlation_CI_Low_HOM)[1] <- "Lower"

correlation_CI_Upper_HOM <- c(corrW5W8_HOM$conf.int[2], corrW5W9_HOM$conf.int[2], corrW5W13_HOM$conf.int[2], corrW5W14_HOM$conf.int[2], corrW5W15_HOM$conf.int[2])
correlation_CI_Upper_HOM <- format(round(correlation_CI_Upper_HOM, 3), nsmall = 3)
correlation_CI_Upper_HOM <- as.data.frame(correlation_CI_Upper_HOM)
names(correlation_CI_Upper_HOM)[1] <- "Upper"

#### <<<>>> Step 3 - Sovereignty Correlations

# Generate subset of respondents for wSOV there is valid data in each of the six panel waves:
subset_correlation_SOV <- c("lfdn", "Sovereignty_Mean_W5",
                            "Sovereignty_Mean_W8", "Sovereignty_Mean_W9",
                            "Sovereignty_Mean_W13", "Sovereignty_Mean_W14",
                            "Sovereignty_Mean_W15")
subset_correlation_SOV <- df_GLES17[subset_correlation_SOV]
subset_correlation_SOV <- subset_correlation_SOV[complete.cases(subset_correlation_SOV), ]
# correlations:
corrW5W8_SOV <- cor.test(x=subset_correlation_SOV$Sovereignty_Mean_W5, 
                         y=subset_correlation_SOV$Sovereignty_Mean_W8, method = 'pearson', exact = FALSE)
corrW5W9_SOV <- cor.test(x=subset_correlation_SOV$Sovereignty_Mean_W5, 
                         y=subset_correlation_SOV$Sovereignty_Mean_W9, method = 'pearson', exact = FALSE)
corrW5W13_SOV <- cor.test(x=subset_correlation_SOV$Sovereignty_Mean_W5, 
                          y=subset_correlation_SOV$Sovereignty_Mean_W13, method = 'pearson', exact = FALSE)
corrW5W14_SOV <- cor.test(x=subset_correlation_SOV$Sovereignty_Mean_W5,
                          y=subset_correlation_SOV$Sovereignty_Mean_W14, method = 'pearson', exact = FALSE)
corrW5W15_SOV <- cor.test(x=subset_correlation_SOV$Sovereignty_Mean_W5, 
                          y=subset_correlation_SOV$Sovereignty_Mean_W15, method = 'pearson', exact = FALSE)

# Estimates & CIs
correlation_estimates_SOV <- c(corrW5W8_SOV$estimate, corrW5W9_SOV$estimate, corrW5W13_SOV$estimate, corrW5W14_SOV$estimate, corrW5W15_SOV$estimate)
correlation_estimates_SOV <- format(round(correlation_estimates_SOV, 3), nsmall = 3)
correlation_estimates_SOV <- as.data.frame(correlation_estimates_SOV)
names(correlation_estimates_SOV)[1] <- "correlation"

correlation_CI_Low_SOV <- c(corrW5W8_SOV$conf.int[1], corrW5W9_SOV$conf.int[1], corrW5W13_SOV$conf.int[1], corrW5W14_SOV$conf.int[1], corrW5W15_SOV$conf.int[1])
correlation_CI_Low_SOV <- format(round(correlation_CI_Low_SOV, 3), nsmall = 3)
correlation_CI_Low_SOV <- as.data.frame(correlation_CI_Low_SOV)
names(correlation_CI_Low_SOV)[1] <- "Lower"

correlation_CI_Upper_SOV <- c(corrW5W8_SOV$conf.int[2], corrW5W9_SOV$conf.int[2], corrW5W13_SOV$conf.int[2], corrW5W14_SOV$conf.int[2], corrW5W15_SOV$conf.int[2])
correlation_CI_Upper_SOV <- format(round(correlation_CI_Upper_SOV, 3), nsmall = 3)
correlation_CI_Upper_SOV <- as.data.frame(correlation_CI_Upper_SOV)
names(correlation_CI_Upper_SOV)[1] <- "Upper"

# single dataframe
correlation_table_dimension <- as.data.frame(cbind(rbind(correlation_estimates_AE, 
                                                         correlation_estimates_HOM,
                                                         correlation_estimates_SOV),
                                                   rbind(correlation_CI_Upper_AE,
                                                         correlation_CI_Upper_HOM,
                                                         correlation_CI_Upper_SOV),
                                                   rbind(correlation_CI_Low_AE, 
                                                         correlation_CI_Low_HOM,
                                                         correlation_CI_Low_SOV)))
correlation_table_dimension$correlation <- as.numeric(correlation_table_dimension$correlation)
correlation_table_dimension$Lower <- as.numeric(correlation_table_dimension$Lower)
correlation_table_dimension$Upper <- as.numeric(correlation_table_dimension$Upper)

# add time variable
correlation_table_dimension$time <- c(0.08333333, 0.5, 2.666667, 3.166667, 3.583333,
                                      0.08333333, 0.5, 2.666667, 3.166667, 3.583333,
                                      0.08333333, 0.5, 2.666667, 3.166667, 3.583333)

# Add grouping variable (by variable)
correlation_table_dimension$Variable <- rep(c(1:3), each = 5)
correlation_table_dimension$Variable <- factor(correlation_table_dimension$Variable,
                                               levels = c(1,2,3),
                                               labels = c("Anti-Elitism", "Homogeneity",
                                                          "People Sovereignty"))
## Plot
correlation_Wave1_Others_Dimensions_plot <- ggplot(correlation_table_dimension, 
                                                   aes(x=time, 
                                                       y=correlation,
                                                       shape=Variable,
                                                       color=Variable )) +
  geom_point(aes(y=correlation), size=1.2) +
  geom_line(linetype="dashed", size = 0.25) +
  ylab("Correlation (Pearson's r)") +
  xlab("Time lapsed since first measurement (in years)") +
  theme_minimal() +
  theme(legend.position="bottom") + 
  scale_color_manual(values=c("Anti-Elitism"="#000000",
                              "Homogeneity"="#56B4E9",
                              "People Sovereignty"="#E69F00")) + 
  base_breaks_x1(correlation_table_dimension$time) +
  base_breaks_y1(correlation_table_dimension$correlation)+
  guides(color=guide_legend(nrow=1,byrow=TRUE))


#### >>> Safe Plot 

tiff("APPENDIX_5_correlation_Wave1_Dimensions_plot.tiff",
     units="in", width=6.5, height=4.5, res=600, compression = "lzw")
correlation_Wave1_Others_Dimensions_plot
dev.off()


######################################################################################/
#### <<>> APPENDIX 5 - Figure A5.2 - Stability for individual populist dimensions (global)  ####
#######################################################################################/

# plot - populism plus comparison concepts
plot_desc_overtime_dim <- df_stable_plot %>%
  filter(!is.na(freq) & Category=="Unstable" & var!="Populism" & 
           var!="Political \n Interest" & var!="Satisfaction \n with Government" &
           var!="Economic \n Perceptions" & var!="Climate \n Protection") %>%
  ggplot(., aes(x=time_lapsed, y=freq, colour=var, shape=var, group=var)) +
  geom_point(size=2) +
  geom_line() + 
  scale_color_manual(values=c("Anti-Elitism"="#000000",
                              "People Sovereignty"="#E69F00",
                              "Homogeneity"="#56B4E9")) +
  base_breaks_x3(df_stable_plot$time_lapsed) +
  base_breaks_y3(df_stable_plot$freq) +
  scale_y_continuous(labels=scales::percent) +
  theme_minimal() +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  xlab("") +
  ylab("Percent") +
  xlab("Time since first measurement (years)") +
  guides(color=guide_legend(nrow=1, byrow=TRUE))  

#### Safe Plot

tiff("APPENDIX_5_FIGURE_5.2_PopDim_Over_Time_Desc.tiff",
     units="in", width=8, height=6, res=900, compression = "lzw")
plot_desc_overtime_dim
dev.off()

######################################################################################/
#### <<>> APPENDIX 5 - Table A5.1 - Within respondents absolute change and sd for dimensions  ####
#######################################################################################/

# tabulate
df_abs_analysis
#rows 8-10

#############################################################################################/
#### <<>> APPENDIX 5 - Figure 5.3 - Correlations for Multiplied Populist Scale (Appendix) ####
#############################################################################################/

## Correlations already run, all that is left is to combine this into a dataframe and plot:

# single dataframe (for minimum and multiplied populism score)
correlation_table_c <- as.data.frame(rbind(df_correlation_estimates_complete_b,
                                           df_correlation_estimates_complete_b_mult))

# Add grouping variable (by variable)
correlation_table_c$Variable <- rep(c(1:2), each = 5)
correlation_table_c$Variable <- factor(correlation_table_c$Variable,
                                       levels = c(1:2),
                                       labels = c("Populism \n (Minimum)",
                                                  "Populism \n (Multiplied)"))
# Add results from individual dimensions:
correlation_table_c <- rbind(correlation_table_c, correlation_table_dimension)

# Plot
correlation_Wave1_Populism_Multiplied_plot <- ggplot(correlation_table_c, 
                                                     aes(x=time, 
                                                         y=correlation,
                                                         shape=Variable,
                                                         color=Variable )) +
  geom_point(aes(y=correlation), size=1.2) +
  geom_line(linetype="dashed", size = 0.25) +
  ylab("Correlation (Pearson's r)") +
  xlab("Time lapsed since first measurement (in years)") +
  theme_minimal() +
  theme(legend.position="bottom") + 
  scale_color_manual(values=c("Populism \n (Minimum)"="#000000",
                              "Populism \n (Multiplied)"="#CC79A7",
                              "Anti-Elitism"="#E69F00",
                              "Homogeneity"="#56B4E9",
                              "People Sovereignty"="#009E73")) + 
  base_breaks_x1(correlation_table_c$time) +
  base_breaks_y1(correlation_table_c$correlation)+
  guides(color=guide_legend(nrow=2,byrow=TRUE))


#### >>> Safe Plot 

tiff("APPENDIX_5_FIGURE_5.3_correlation_Wave1_Populism_Multiplied_plot.tiff",
     units="in", width=6.5, height=4.5, res=600, compression = "lzw")
correlation_Wave1_Populism_Multiplied_plot
dev.off()

######################################################################################/
#### <<>> APPENDIX 5 - Figure 5.4- Stable Non-Populists and Populists - Goertz Multiplied Populism Score (Global Analysis) ####
######################################################################################/

## Plot shows unstable populist attitude holders (INCLUDING those who are consistently
## in the "neither/nor" category in all six panel waves).

#### <<<>>> Step 1: Summarize data 

#Summarize Data - W5W8
# Populism
tab_mutliplied_a_pop <- df_GLES17 %>%
  select(starts_with("StablePop_Mult_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_Mult_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=1) %>%
  rename(Category=StablePop_Mult_W5W8)

####Summarize Data - W5W9
#Populism
tab_mutliplied_b_pop <- df_GLES17 %>%
  select(starts_with("StablePop_Mult_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_Mult_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=1) %>%
  rename(Category=StablePop_Mult_W5W9)


#Summarize Data - W5W13
#Populism
tab_mutliplied_c_pop <- df_GLES17 %>%
  select(starts_with("StablePop_Mult_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_Mult_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=1) %>%
  rename(Category=StablePop_Mult_W5W13)


#Summarize Data - W5W14
#Populism
tab_mutliplied_d_pop <- df_GLES17 %>%
  select(starts_with("StablePop_Mult_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_Mult_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=1) %>%
  rename(Category=StablePop_Mult_W5W14)


#Summarize Data - W5W15
#Populism
tab_mutliplied_e_pop <- df_GLES17 %>%
  select(starts_with("StablePop_Mult_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_Mult_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=1) %>%
  rename(Category=StablePop_Mult_W5W15)


#Build dataset for plot:
df_stable_plot_mutliplied <- as.data.frame(rbind(tab_mutliplied_a_pop, tab_mutliplied_b_pop, tab_mutliplied_c_pop, 
                                                 tab_mutliplied_d_pop, tab_mutliplied_e_pop))
df_stable_plot_mutliplied$freq <- round(df_stable_plot_mutliplied$freq,2)

# Add time lapsed variable
df_stable_plot_mutliplied$time_lapsed <- NA
df_stable_plot_mutliplied$time_lapsed[df_stable_plot_mutliplied$time==1] <- 0.08333333
df_stable_plot_mutliplied$time_lapsed[df_stable_plot_mutliplied$time==2] <- 0.5
df_stable_plot_mutliplied$time_lapsed[df_stable_plot_mutliplied$time==3] <- 2.666667
df_stable_plot_mutliplied$time_lapsed[df_stable_plot_mutliplied$time==4] <- 3.166667
df_stable_plot_mutliplied$time_lapsed[df_stable_plot_mutliplied$time==5] <- 3.583333

#Add value labels:
df_stable_plot_mutliplied$Category <- factor(df_stable_plot_mutliplied$Category,
                                             labels=c("Unstable", "Stable \n Positive",
                                                      "Stable \n Negative"))
df_stable_plot_mutliplied$time <- factor(df_stable_plot_mutliplied$time,
                                         labels=c("1", "2",
                                                  "3", "4",
                                                  "5"))
df_stable_plot_mutliplied$var <- factor(df_stable_plot_mutliplied$var,
                                        labels=c("Populism \n (Multiplied)"))

## Add data for two-dimensional populism variable, individual dimensions,
## and concepts for comparison

df_stable_plot_mutliplied <- rbind(df_stable_plot_mutliplied,
                                   df_stable_plot_V2,
                                   #the correct versions for the individual dimensions
                                   #with the stable middle category respondents coded
                                   #as stable are in a different df
                                   df_stable_plot[df_stable_plot$var=="Anti-Elitism",],
                                   df_stable_plot[df_stable_plot$var=="People Sovereignty",],
                                   df_stable_plot[df_stable_plot$var=="Homogeneity",])
# adjust levels for variables for clarity:
levels(df_stable_plot_mutliplied$var) <- c("Populism \n (Multiplied)", 
                                           "Populism \n (Minimum)", 
                                           "Political \n Interest",
                                           "Satisfaction \n with Government",
                                           "Economic \n Perceptions",
                                           "Climate \n Change",
                                           "Climate \n Protection",
                                           "Anti-Elitism",
                                           "People Sovereignty",
                                           "Homogeneity")

#### <<<>>> Step 2: plot 

# plot
plot_desc_overtime_pop_multiplied <- df_stable_plot_mutliplied %>%
  filter(!is.na(freq) & Category=="Unstable" & var=="Populism \n (Multiplied)" |
           !is.na(freq) & Category=="Unstable" & var=="Populism \n (Minimum)" |
           !is.na(freq) & Category=="Unstable" & var=="Anti-Elitism" |
           !is.na(freq) & Category=="Unstable" & var=="People Sovereignty" |
           !is.na(freq) & Category=="Unstable" & var=="Homogeneity") %>%
  ggplot(., aes(x=time_lapsed, y=freq, colour=var, shape=var, group=var)) +
  geom_point(size=2) +
  geom_line() + 
  scale_color_manual(values=c("#CC79A7","#000000", "#E69F00", "#009E73", "#56B4E9")) +
  base_breaks_x3(df_stable_plot_mutliplied$time_lapsed) +
  base_breaks_y3(df_stable_plot_mutliplied$freq) +
  scale_y_continuous(labels=scales::percent) +
  theme_minimal() +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  xlab("") +
  ylab("Percent") +
  xlab("Time lapsed since first measurement (in years)") +
  guides(color=guide_legend(nrow=1, byrow=TRUE)) 

#### Safe Plot

tiff("APPENDIX_5_FIGURE_5.4_Pop_Over_Time_Desc_multiplied.tiff",
     units="in", width=8, height=6, res=900, compression = "lzw")
plot_desc_overtime_pop_multiplied
dev.off()

####################################################################################################/
#### <<>> APPENDIX 5 - Figure 5.5 - Correlations for Two-Dimensional Populist Scale (Appendix)  ####
####################################################################################################/

# This over time plot shows the correlation for the minimum score based on a 
# two-dimensional populist scale that combines the dimensions "People's Sovereignty"
# and "Anti-Elitism".

# single dataframe (for minimum and multiplied populism score)
correlation_table_d <- as.data.frame(rbind(df_correlation_estimates_complete_b,
                                           df_correlation_estimates_complete_c_twodim))

# Add grouping variable (by variable)
correlation_table_d$Variable <- rep(c(1:2), each = 5)
correlation_table_d$Variable <- factor(correlation_table_d$Variable,
                                       levels = c(1:2),
                                       labels = c("Populism \n (3 Dimensions)",
                                                  "Populism \n (2 Dimensions)"))

# Plot
correlation_Wave1_Populism_TwoDimensions_plot <- ggplot(correlation_table_d, 
                                                        aes(x=time, 
                                                            y=correlation,
                                                            shape=Variable,
                                                            color=Variable )) +
  geom_point(aes(y=correlation), size=1.2) +
  geom_line(linetype="dashed", size = 0.25) +
  ylab("Correlation (Pearson's r)") +
  xlab("Time lapsed since first measurement (in years)") +
  theme_minimal() +
  theme(legend.position="bottom") + 
  scale_color_manual(values=c("Populism \n (3 Dimensions)"="#000000",
                              "Populism \n (2 Dimensions)"="#CC79A7")) + 
  base_breaks_x1(correlation_table_c$time) +
  base_breaks_y1(correlation_table_c$correlation)+
  guides(color=guide_legend(nrow=1,byrow=TRUE))

#### >>> Safe Plot 

tiff("APPENDIX_5_Figure_5.5_correlation_Wave1_Populism_TwoDimensions_plot.tiff",
     units="in", width=6.5, height=4.5, res=600, compression = "lzw")
correlation_Wave1_Populism_TwoDimensions_plot
dev.off()

######################################################################################/
#### <<>> APPENDIX - Figure 5.6 - Stable Non-Populists and Populists - Two-Dimensional Populism Score (Global Analysis) ####
######################################################################################/

## Plot shows unstable populist attitude holders.

#### <<<>>> Step 1: Summarize data 

#Summarize Data - W5W8
# Populism
tab_twodim_a_pop <- df_GLES17 %>%
  select(starts_with("StablePop_TwoDim_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_TwoDim_W5W8)%>%
  mutate(freq = n / sum(n),
         time=1,
         var=1) %>%
  rename(Category=StablePop_TwoDim_W5W8)

####Summarize Data - W5W9
#Populism
tab_twodim_b_pop <- df_GLES17 %>%
  select(starts_with("StablePop_TwoDim_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_TwoDim_W5W9)%>%
  mutate(freq = n / sum(n),
         time=2,
         var=1) %>%
  rename(Category=StablePop_TwoDim_W5W9)


#Summarize Data - W5W13
#Populism
tab_twodim_c_pop <- df_GLES17 %>%
  select(starts_with("StablePop_TwoDim_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_TwoDim_W5W13)%>%
  mutate(freq = n / sum(n),
         time=3,
         var=1) %>%
  rename(Category=StablePop_TwoDim_W5W13)


#Summarize Data - W5W14
#Populism
tab_twodim_d_pop <- df_GLES17 %>%
  select(starts_with("StablePop_TwoDim_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_TwoDim_W5W14)%>%
  mutate(freq = n / sum(n),
         time=4,
         var=1) %>%
  rename(Category=StablePop_TwoDim_W5W14)


#Summarize Data - W5W15
#Populism
tab_twodim_e_pop <- df_GLES17 %>%
  select(starts_with("StablePop_TwoDim_W")) %>%
  filter(complete.cases(.)) %>%
  count(StablePop_TwoDim_W5W15)%>%
  mutate(freq = n / sum(n),
         time=5,
         var=1) %>%
  rename(Category=StablePop_TwoDim_W5W15)


#Build dataset for plot:
df_stable_plot_twodim <- as.data.frame(rbind(tab_twodim_a_pop, tab_twodim_b_pop, tab_twodim_c_pop, 
                                             tab_twodim_d_pop, tab_twodim_e_pop))
df_stable_plot_twodim$freq <- round(df_stable_plot_twodim$freq,2)

# Add time lapsed variable
df_stable_plot_twodim$time_lapsed <- NA
df_stable_plot_twodim$time_lapsed[df_stable_plot_twodim$time==1] <- 0.08333333
df_stable_plot_twodim$time_lapsed[df_stable_plot_twodim$time==2] <- 0.5
df_stable_plot_twodim$time_lapsed[df_stable_plot_twodim$time==3] <- 2.666667
df_stable_plot_twodim$time_lapsed[df_stable_plot_twodim$time==4] <- 3.166667
df_stable_plot_twodim$time_lapsed[df_stable_plot_twodim$time==5] <- 3.583333

#Add value labels:
df_stable_plot_twodim$Category <- factor(df_stable_plot_twodim$Category,
                                         labels=c("Unstable", "Stable \n Positive",
                                                  "Stable \n Negative",
                                                  "Stable \n Middle"))
df_stable_plot_twodim$time <- factor(df_stable_plot_twodim$time,
                                     labels=c("1", "2",
                                              "3", "4",
                                              "5"))
df_stable_plot_twodim$var <- factor(df_stable_plot_twodim$var,
                                    labels=c("Populism \n (2 Dimensions)"))

## Add data for two-dimensional populism variable, individual dimensions,
## and concepts for comparison

df_stable_plot_twodim <- rbind(df_stable_plot_twodim,
                               df_stable_plot_V2,
                               #the correct versions for the individual dimensions
                               #with the stable middle category respondents coded
                               #as stable are in a different df
                               df_stable_plot[df_stable_plot$var=="Anti-Elitism",],
                               df_stable_plot[df_stable_plot$var=="People Sovereignty",],
                               df_stable_plot[df_stable_plot$var=="Homogeneity",])
# adjust levels for variables for clarity:
levels(df_stable_plot_twodim$var) <- c("Populism \n (2 Dimensions)", 
                                           "Populism \n (3 Dimensions)", 
                                           "Political \n Interest",
                                           "Satisfaction \n with Government",
                                           "Economic \n Perceptions",
                                           "Climate \n Change",
                                           "Climate \n Protection",
                                           "Anti-Elitism",
                                           "People Sovereignty",
                                           "Homogeneity")

#### <<<>>> Step 2: plot 

# plot
plot_desc_overtime_pop_twodim <- df_stable_plot_twodim %>%
  filter(!is.na(freq) & Category=="Unstable" & var=="Populism \n (2 Dimensions)" |
           !is.na(freq) & Category=="Unstable" & var=="Populism \n (3 Dimensions)" |
           !is.na(freq) & Category=="Unstable" & var=="Anti-Elitism" |
           !is.na(freq) & Category=="Unstable" & var=="People Sovereignty" |
           !is.na(freq) & Category=="Unstable" & var=="Homogeneity") %>%
  ggplot(., aes(x=time_lapsed, y=freq, colour=var, shape=var, group=var)) +
  geom_point(size=2) +
  geom_line() + 
  scale_color_manual(values=c("#CC79A7","#000000", "#E69F00", "#009E73", "#56B4E9")) +
  base_breaks_x3(df_stable_plot_twodim$time_lapsed) +
  base_breaks_y3(df_stable_plot_twodim$freq) +
  scale_y_continuous(labels=scales::percent) +
  theme_minimal() +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  xlab("") +
  ylab("Percent") +
  xlab("Time lapsed since first measurement (in years)") +
  guides(color=guide_legend(nrow=1, byrow=TRUE)) 

#### Safe Plot

tiff("APPENDIX_5_Figure_5.6_Pop_Over_Time_Desc_twodim.tiff",
     units="in", width=8, height=6, res=900, compression = "lzw")
plot_desc_overtime_pop_twodim
dev.off()

################################################################################################################/
#### <<>> APPENDIX 6 - Figure 6.1 - Correlation with Democratic Attitudes by Stability (by switch count)    ####
################################################################################################################/

## Correlations by switch count:
df_cor_plot_IT1 <- df_GLES17 %>% 
  group_by(switch.count) %>%
  filter(!is.na(switch.count)) %>%
  mutate(Correlation = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT1_W15,  use = "complete")$estimate,
         CI_Low = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT1_W15,  use = "complete")$conf.int[1],
         CI_Upper = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT1_W15,  use = "complete")$conf.int[2],
         Cor_Variable = 1,
         Distinction = switch.count) %>%
  select(Correlation, CI_Low, CI_Upper, Cor_Variable, Distinction) %>%
  distinct()

df_cor_plot_IT2 <- df_GLES17 %>% 
  group_by(switch.count) %>%
  filter(!is.na(switch.count)) %>%
  mutate(Correlation = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT2_W15,  use = "complete")$estimate,
         CI_Low = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT2_W15,  use = "complete")$conf.int[1],
         CI_Upper = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT2_W15,  use = "complete")$conf.int[2],
         Cor_Variable = 2,
         Distinction = switch.count) %>%
  select(Correlation, CI_Low, CI_Upper, Cor_Variable, Distinction) %>%
  distinct()

df_cor_plot_IT3 <- df_GLES17 %>% 
  group_by(switch.count) %>%
  filter(!is.na(switch.count)) %>%
  mutate(Correlation = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT3_W15,  use = "complete")$estimate,
         CI_Low = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT3_W15,  use = "complete")$conf.int[1],
         CI_Upper = cor.test(x=Populism_Goertz_AbsoluteMinimum_W15, y=DemAtt_IT3_W15,  use = "complete")$conf.int[2],
         Cor_Variable = 3,
         Distinction = switch.count) %>%
  select(Correlation, CI_Low, CI_Upper, Cor_Variable, Distinction) %>%
  distinct()

## Combine
df_cor_plot_Count_App <- as.data.frame(rbind(df_cor_plot_IT1, df_cor_plot_IT2, df_cor_plot_IT3))
df_cor_plot_Count_App$Cor_Variable <- as.factor(df_cor_plot_Count_App$Cor_Variable)
levels(df_cor_plot_Count_App$Cor_Variable) <- c("Every party should have \n the chance to become part \n of the government.",
                                      "Everyone should have the \n right to stand up for their \n opinion even if the  \n majority has a different opinion", 
                                      "A vibrant democracy is \n unthinkable without an opposition.")

## Plot
df_test_cor_plot_count <- df_cor_plot_Count_App %>%
  ggplot(.,
         aes(x=Distinction, y=Correlation, color = as.factor(Distinction))) + 
  geom_pointrange(aes(ymin=CI_Low, ymax=CI_Upper), size=0.7) +
  geom_hline(yintercept=0, color='red', size=0.5)+
  facet_wrap( ~ Cor_Variable)+
  coord_flip()+
  xlab("")+
  theme_minimal() +
  base_breaks_x1(df_cor_plot_Count_App$Distinction) +
  base_breaks_y1(df_cor_plot_Count_App$Correlation) +
  theme(legend.position="bottom") +
  ylim(-0.3, 0.5) +
  scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2")) +
  theme(legend.position = "none") +
  xlab("Switch Count")

#### Safe Plot

tiff("APPENDIX6_Figure_6.1Corellation_Democratic_Attitudes_Appendix.tiff",
     units="in", width=8, height=4.5, res=900, compression = "lzw")
df_test_cor_plot_count
dev.off()

#################################################################################################################/
#### /// Statistic - Populist Attitudes and Vote Choice                                                      ####
################################################################################################################/


#### <<>> Table A6.1 ####
# reported vote for AfD by Populist Ideas and Absolute Change in pop attitudes
# over time (variables created for main text analyses, see section on Table 4)
df_GLES17 %>%
  filter(!is.na(Dummy_PopVote) & !is.na(Pop_W5_W15_Av_Abs) & !is.na(Populism_Cat_V1_W5) & !is.na(StablePop_V2_W5W15)) %>%
  group_by(Populism_Cat_V1_W5, Dummy_PopVote) %>%
  summarise(mean_abs = mean(Pop_W5_W15_Av_Abs, na.rm=T),
            mean_sd = mean(Pop_W5_W15_sd_Abs, na.rm=T)) 

#### <<<>>> Table A6.2 - replicating main analyses and using switch count ####

## Testing the extent to which those who AGREE with populist ideas were less likely to 
## report voting for AfD.
# - combined (unstable and stable)
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4])),2)
# - switch count 0
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$switch.count==0])),2)
# - switch count 1
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$switch.count==1])),2)
# - switch count 2
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$switch.count==2])),2)
# - switch count 3
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$switch.count==3])),2)
# - switch count 4
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$switch.count==4])),2)
# - switch count 5
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$switch.count==5])),2)

## Testing the extent to which those who DISAGREE with populist ideas were less likely to 
## report voting for AfD.
# - combined (unstable and stable)
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3])),2)
# - switch count 0
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$switch.count==0])),2)
# - switch count 1
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$switch.count==1])),2)
# - switch count 2
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$switch.count==2])),2)
# - switch count 3
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$switch.count==3])),2)
# - switch count 4
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$switch.count==4])),2)
# - switch count 5
round(prop.table(table(df_GLES17$Dummy_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$switch.count==5])),2)

#### <<<>>> Analysis for Appendix: Mainstream vs AfD vs DieLinke ####

## Three category List Vote (0=mainstream, 1=AfD, 2=DieLinke):
df_GLES17$Three_PopVote <- NA
df_GLES17$Three_PopVote[df_GLES17$Vote_List_W58!=5 & df_GLES17$Vote_List_W58!=6] <- 0 #Mainstream
df_GLES17$Three_PopVote[df_GLES17$Vote_List_W58==6] <- 1 #AfD
df_GLES17$Three_PopVote[df_GLES17$Vote_List_W58==5] <- 2 #DieLinke

## Testing the extent to which those who AGREE with populist ideas were likely to 
## report voting for AfD and Die Linke.
# - combined (unstable and stable)
round(prop.table(table(df_GLES17$Three_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4])),2)
# - unstable
round(prop.table(table(df_GLES17$Three_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$StablePop_V2_W5W15==1])),2)
# - stable
round(prop.table(table(df_GLES17$Three_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5>=4 &
                                                 df_GLES17$StablePop_V2_W5W15>1])),2)

## Testing the extent to which those who DISAGREE with populist ideas were less likely to 
## report voting for AfD and Die Linke.
# - combined (unstable and stable)
round(prop.table(table(df_GLES17$Three_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3])),2)
# - unstable
round(prop.table(table(df_GLES17$Three_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$StablePop_V2_W5W15==1])),2)
# - stable
round(prop.table(table(df_GLES17$Three_PopVote[df_GLES17$Populism_Goertz_AbsoluteMinimum_W5<3 &
                                                 df_GLES17$StablePop_V2_W5W15>1])),2)


###############################################################################/
#### <<>> APPENDIX 7 - Table 7.1 Statistic - Explaining Stability          ####
###############################################################################/

## the following is a simple logistic model to capture what factors can explain
## the groups (stable populist attitudes or unstable populist attitudes)
## respondents fall into. The independent variables are attitude extremity in 
## Wave 1, Age, University Education (yes/no), partisanship (yes/no), region
## (East/West Germany), turnout in 2017 election (as proxy for political involvement)

## Prep dependent variable that combines stability groups
df_GLES17$StablePop_W5W15_Com <- NA
df_GLES17$StablePop_W5W15_Com[df_GLES17$StablePop_V2_W5W15==1] <- 1
df_GLES17$StablePop_W5W15_Com[df_GLES17$StablePop_V2_W5W15>1] <- 2
df_GLES17$StablePop_W5W15_Com <- as.factor(df_GLES17$StablePop_W5W15_Com)
levels(df_GLES17$StablePop_W5W15_Com) <- c("Unstable", "Stable")

## Fit model - logit
glm_stability <- glm(StablePop_W5W15_Com  ~ PolInt_W5 + Populism_Extremity_W5 + PiD + Turnout +
                     Age + Uni_Edu + ostwest, data=df_GLES17, family = "binomial")

## Fit model - negative binomial with number of switches as dependent variable
glm.nb_stability <- glm.nb(switch.count  ~ PolInt_W5 + Populism_Extremity_W5 + PiD + Turnout +
         Age + Uni_Edu + ostwest, data=df_GLES17)

## Tables:
stargazer(glm_stability, glm.nb_stability,
          type = "html",
          out="Reg_Tables.doc",
          digits = 2,
          star.cutoffs = c(0.05, 0.01, 0.001))

############################ END OF R-SCRIPT ##############################